java对象/map 转换成json
public static final ObjectMapper MAPPER = new ObjectMapper();
String json = MAPPER.writeValueAsString(Object obj);
json转对象
方式一: 直接转对象,对象中的属性和json格式key 一致。
Object obj = MAPPER.readValue(json, Object.class);
方式二:通用(json数据中有集合)
JsonNode jsonNode = MAPPER.readTree("json");
ArrayNode jsonNode2 = (ArrayNode) jsonNode.get("data"); // data 是集合名
for (JsonNode jsonNode3 : jsonNode2) { // jsonNode3 代表集合中的每一个属性
int a = jsonNode3.get("集合中属性名").asInt();// asText()....转成相应的类型
}
例: json直接转对象
返回的json格式:{
"status":200,
"data":{ "id":7,
"username":"xiaoxiao",
"phone":"13969035106",
"email":null,
"created":1517574817000,
"updated":1517574817000
},
"msg":"ok"
}
String map = apiService.doGet("http://sso.taotao.com/sso/user/" + token);
// map 转 json
JsonNode jsonNode = MAPPER.readTree(map);
String jsonUser =jsonNode.get("data").toString();
System.err.println(jsonUser + "<------------------------");
return MAPPER.readValue(jsonUser, User.class);
集合通用转换:
JsonNode jsonNode = PropertiesService.MAPPER.readTree(jsonData);
//取出总记录数
// int total = jsonNode.get("total").asInt();
// System.out.println("总记录数: total=" + total);
ArrayNode arrayNode = (ArrayNode) jsonNode.get("rows");
List<Map<String,Object>> ad1List = new ArrayList<Map<String,Object>>();
for(JsonNode jn : arrayNode){
Map<String,Object> map = new HashMap<String,Object>();
String imageUrl = jn.get("url").asText();
String imagePath = jn.get("pic").asText();
String title = jn.get("title")==null ? "" : jn.get("title").asText();
map.put("srcB", imagePath);
map.put("height",240 );
map.put("alt", title);
map.put("width", 670);
map.put("src", imagePath);
map.put("widthB",550 );
map.put("href", imageUrl);
map.put("heightB",240 );
ad1List.add(map);
}