Student o = JSONObject.parseObject(jsonString, Student.class);
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>>>() {});
JSON.toJSONString(user);
JSON.toJSONString(users);
String json = "";
JSONObject jsonObject = JSON.parseObject(json);
//使用方法
jsonObject.getString(key);
简单类型的:(json字段与接收字段一致的时候)
例:json:
{
"count": 3,
"servers": [{
"fault": null,
"id": "5c1ac257-",
"cpu_options": {
"hw:cpu_threads": null
}
}]
}
JSONObject jsonObject = JSON.parseObject(json);
// 获取到我们的jsonobject参数,并toJSONString
String s = JSONArray.toJSONString(jsonObject.get("servers"));
// 将json字符串转换为集合对象(实体类就省略了啊)
List<AnswerCardVo> cardVos = JSONArray.parseArray(s, AnswerCardVo.class);
//直接调用new方法
JSONObject jsonObject = new JSONObject(map);
例: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;
}
方法一:
@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)