fastjson Map类的容器反序列化后的数据类型丢失了,是否有办法解决这样的问题?

bzzcjhmw  于 2021-11-27  发布在  Java
关注(0)|答案(1)|浏览(413)
package test.fastjson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

public class JsonTest {

	static class Holder{
		private HashMap<Integer,Object> vals = new HashMap<>();

		public HashMap<Integer, Object> getVals() {
			return vals;
		}

		public void setVals(HashMap<Integer, Object> vals) {
			this.vals = vals;
		}	

	}

	public static void main(String[] args){
		Holder holder = new Holder();
		List<Integer> array = new ArrayList<>();
		array.add(1);
		array.add(2);
		holder.vals.put(1, array);
		System.out.println("holder.getVals().get(1).getClass()="+holder.getVals().get(1).getClass());
		String json = JSON.toJSONString(holder, new SerializerFeature[] { SerializerFeature.WriteClassName, SerializerFeature.DisableCircularReferenceDetect });
		System.out.println(json);
		Holder holder2 = JSON.parseObject(json, Holder.class);
		System.out.println("holder2.getVals().get(1).getClass()="+holder2.getVals().get(1).getClass());

	}
}

实际输出发现反序列化类型已经丢失了。。。

holder.getVals().get(1).getClass()=class java.util.ArrayList
{"@type":"test.fastjson.JsonTest$Holder","vals":{"@type":"java.util.HashMap",1:[1,2]}}
holder2.getVals().get(1).getClass()=class com.alibaba.fastjson.JSONArray

现在有其他的SerializerFeature 支持这种情况吗

uajslkp6

uajslkp61#

换了jackson测试了一下,发现jackson没这个问题

private static void jackson() throws JsonParseException, JsonMappingException, IOException{
		Holder holder = new Holder();
		List<Integer> array = new ArrayList<>();
		array.add(1);
		array.add(2);
		holder.vals.put(1, array);
		System.out.println("holder.getVals().get(1).getClass()="+holder.getVals().get(1).getClass());
		ObjectMapper objectMapper = new  ObjectMapper();  
		String json = objectMapper.writeValueAsString(holder);
		System.out.println(json);
		Holder holder2 = objectMapper.readValue(json, Holder.class);
		System.out.println("holder2.getVals().get(1).getClass()="+holder2.getVals().get(1).getClass());

	}

输出:

holder.getVals().get(1).getClass()=class java.util.ArrayList
{"vals":{"1":[1,2]}}
holder2.getVals().get(1).getClass()=class java.util.ArrayList

相关问题