com.alibaba.fastjson包下相关方法
JSON相关
1.json转对象
Student o = JSONObject.parseObject(jsonString, Student.class);
2.json转List
json: 花括号{}
String jsonString = “[{"id":1, "name": "zhangsan", "sex": "male", "age": 18, :city": "Beijing"},{"id": 2, "name": "lisi", "sex": "female", "age": 18, "city": "Shanghai"}]”
List<Student> studentList = JSONObject.parseArray(jsonString, Student.class);
json: 方括号[] 将JSON字符串看成是list嵌套list的格式,即List< List< Object> >,获取到list之后,循环list,依次获取内层List< Object >,通过get(0)获取id,get(1)获取name……。
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
简单类型的:(json字段与接收字段一致的时候) 例:json:
{
"count": 3,
"servers": [{
"fault": null,
"id": "5c1ac257-",
"cpu_options": {
"hw:cpu_threads": null
}
}]
}
JSONObject jsonObject = JSON.parseObject(json);
String s = JSONArray.toJSONString(jsonObject.get("servers"));
List<AnswerCardVo> cardVos = JSONArray.parseArray(s, AnswerCardVo.class);
4.Map转JSONObject
JSONObject jsonObject = new JSONObject(map);
以上内容是接收字段与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>>(){});
|