首先引入jar包:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.83</version>
</dependency>
JSON相关
1.json转对象
Student o = JSONObject.parseObject(jsonString, Student.class);
2.json转List
List<Student> studentList = JSONObject.parseArray(jsonString, Student.class);
或者
String jsonString = “[[1,"zhangsan","male",18,"Beijing"],[2,"lisi","female",18,"Shanghai"]]”
List<List<Object>> list = JSON.parseObject([jsonString], new TypeReference<List<List<Object>>>() {});
3.对象转json
JSON.toJSONString(user);
4.List转json
JSON.toJSONString(users);
JSONObject相关:
1.json转JSONObject方法
String json = "";
JSONObject jsonObject = JSON.parseObject(json);
2.JSONObject转json方法
jsonObject.getString(key);
3.JSONObject转List
JSONObject jsonObject = JSON.parseObject(json);
// 获取到我们的jsonobject参数,并toJSONString
String s = JSONArray.toJSONString(jsonObject.get("servers"));
// 将json字符串转换为集合对象(实体类就省略了啊)
List<AnswerCardVo> cardVos = JSONArray.parseArray(s, AnswerCardVo.class);
4.Map转JSONObject
//直接调用new方法
Map map1 = new HashMap();
map1.put("one",users1);
map1.put("two",users1);
JSONObject mapJsonObject =(JSONObject) JSONObject.toJSON(map1);
System.out.println(mapJsonObject);
以上内容是接收字段与json字段一致的时候,那么不一致的时候怎么处理?
com.fasterxml.jackson包
例:json串内容如下,要转成List
注意:可以看到,该json串中属性名是这样的OS-EXT-STS:task_state,那么我们接收的bean就无法写成这个属性名去接收,所以需要在接收Bean中使用注解@JsonProperty进行处理
json串
{
"count": 3,
"servers": [{
"fault": null,
"id": "5c1ac257-",
"OS-EXT-STS:task_state": null,
"cpu_options": {
"hw:cpu_threads": null
}
}]
}
可以看到注解@JsonProperty中指定了要接收哪个的值,这样就可以正常转换了
对象:
public class HwInstance {
private String fault;
private String id;
@JsonProperty("OS-EXT-STS:task_state")
private String state;
@JsonProperty("cpu_options")
private Object options;
}
转List
方法一:
@Autowired
private ObjectMapper objectMapper;
String json = "";
JSONObject jsonObject = JSON.parseObject(json);
JavaType javaType = objectMapper.getTypeFactory().constructParametricType(ArrayList.class, HwInstance.class);
List<HwInstance> instances = objectMapper.readValue(objectMapper.readTree(jsonObject.toJSONString()).get("servers").toString(), javaType);
方法二:
@Autowired
private ObjectMapper objectMapper;
String json = "";
List<HwInstance> instances = objectMapper.readValue(objectMapper.readTree(json).get("servers").toString(),new TypeReference<List<HwInstance>>(){});
注意:可能会遇到报错的情况如下:
报错信息:com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field “isleader”
意思是json’中的字段与实体类不匹配,解决办法如下:
办法一:给objectMapper设置一个属性
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
办法二:给实体类加一个注解
@JsonIgnoreProperties(ignoreUnknown = true)
创作不易,如果这篇文章对你有用,请点赞。有其他建议请在下方留言评论,谢谢♪(・ω・)ノ!