本文介绍用fastjson在各个需求间转换最快最简洁的方法
Json字符串>对应Object
Test test = JSON.parseObject(jsonSt, Test.class);//转对应obj
List<Test> list = JSON.parseArray(jsonListSt, Test.class);//转对应list
Json字符串>JsonObject、JsonArray(Map、List)
JSONObject jo = JSON.parseObject(jsonSt);//JSONObject本身就是map
JSONArray ja = JSON.parseArray(jsonListSt);//JSONArray本身就是list
Object>Json字符串
String st = JSON.toJSONString(obj);
Object、ListObject、Map>JsonObject、JsonArray
JSONObject jo = (JSONObject) JSON.toJSON(obj);//什么都没指定就是JSONObject或JSONArray自行强转即可
JSONArray ja = (JSONArray) JSON.toJSON(listObj);//转JSONArray:方法1
JSONArray ja2 = new JSONArray(new ArrayList<>(listObj));//转JSONArray:方法2,这个和上面一样,源代码也差不多
JSONObject joMap = new JSONObject(new HashMap<>(mapObj));//map转JSONObject
JsonObject、JsonArray>对应Object
Test test1 = jo.toJavaObject(Test.class);//JsonObject转对象:方法1
Test test2 = JSON.toJavaObject(jo, Test.class);//JsonObject转对象:方法2,和上面源码是一样的
List<Test> listTest = ja.toJavaList(Test.class);//JsonArray转对象,源码就是for循环一个个转...(jar版本1.2.23或1.1.72.android及以上)
JsonObject、JsonArray>Json字符串
直接toString就行了
List<Map<String,?>>、Map<String,?>>对应对象
Test test1 = JSON.toJavaObject(new JSONObject(new HashMap<>(map)), Test.class);//Map转对应对象:方法1,标准写法
Test test2 = new JSONObject(new HashMap<>(map)).toJavaObject(Test.class);//Map转对应对象:方法2,标准写法
Test test3 = TypeUtils.cast(map, Test.class, ParserConfig.getGlobalInstance());//Map转对应对象:方法3,少创建对象写法
List<Test> listTest1 = new JSONArray(new ArrayList<>(listMap)).toJavaList(Test.class);//ListMap转对应对象:方法1,标准写法
ArrayList<Test> listTest = new ArrayList<>();//ListMap转对应对象:方法2,少创建对象写法
for (Map<String, Object> item : listMap) {
listTest.add(TypeUtils.cast(item, Test.class, ParserConfig.getGlobalInstance()));
}
数组转换
其实就是list和一维数组之间的转换
List<Object> list = Arrays.asList(tests1);//转成list,返回的list并非常用的ArrayList,此list的add、remove等无法使用
Test[] tests2 = list.toArray(new Test[list.size()]);//list转数组
其他如所谓的Json字符串转Map我就不再多说了
问1:私有属性怎么解析?
答:见我的另一篇博客,此处不再多写
问2:无法确定json字符串是obj还是list怎么办?
答:先用parse然后判断是JsonObject还是JsonArray了(自己直接判断第一个字符是{或[也是可以的),如下
Object json = JSON.parse(jsonSt);
if (json instanceof JSONObject) {
Test test = ((JSONObject) json).toJavaObject(Test.class);
} else {//除了json
List<Test> listTest = ((JSONArray) json).toJavaList(Test.class);
}
转载请注明出处:王能的博客:https://blog.csdn.net/weimingjue/article/details/87262111