fastjson生成和解析json数据
一、fastjson生成json数据
String
jsonStrng = JSON.toJSONString(object);
二、 fastjson
解析json字符串
1.
JavaBean
User user = JSON.parseObject(jsonString,
User.class);
2. List<JavaBean>
List<User> listPerson =JSON.parseArray(jsonString,
User.class);
3. List<String>
List<String> listString = JSON.parseArray(jsonString, String.class);
4. List<Map<String,Object>>
List<Map<String, Object>> listMap = JSON.parseObject(jsonString, new TypeReference<List<Map<String,Object>>>(){});
三、拓展
1)fastjson生成json数据时,导出空数据。
String jsonStr=JSON.toJSONString(userList,SerializerFeature.WriteMapNullValue);
2)fastjson解析json数据时需要将值为null的key也可以解析出来,就要用到fastjson的反射了。
List<Map<String,
Object>> listMap = JSON.parseObject(jsonString, new TypeReference<List<Map<String,Object>>>(){});
下面的是测试代码,仅供参考。
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.TypeReference; import com.alibaba.fastjson.serializer.SerializerFeature; public class Test { public static void main(String[] args){ List<Map<String,Object>> userList =getUserList(); String jsonStr=JSON.toJSONString(userList,features); System.out.println(jsonStr); List<Map<String, Object>> listMap = JSON.parseObject(jsonStr, new TypeReference<List<Map<String,Object>>>(){}); for(Map<String, Object> map:listMap){ System.out.println(JSON.toJSONString(map,features)); } } public static SerializerFeature[] features=new SerializerFeature[]{ SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullBooleanAsFalse, SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteDateUseDateFormat }; public static List<Map<String,Object>> getUserList(){ List<Map<String,Object>> newList=new ArrayList<Map<String,Object>>(); for(int i=0;i<5;i++){ Map<String,Object> map=new HashMap<String,Object>(); map.put("id", i); map.put("username","xxx"+i); map.put("sex","男"+i); map.put("age",null); map.put("dh",null); map.put("zz","ZZ"+i); newList.add(map); } return newList; } }
版权声明:本文为博主原创文章,未经博主允许不得转载。