java Json
2019獨角獸企業重金招聘Python工程師標準>>>
1、gson
2、jackson
當使用 @JsonProperty參數時,在解析json的時候則不能使用gson.否則會解析無效。
注意一定要用包import com.fasterxml.jackson.databind.ObjectMapper;(高級版本)
而不要用import org.codehaus.jackson.map.ObjectMapper; 如: CatTest
import com.fasterxml.jackson.annotation.JsonProperty;/*** @author :taohong.ouyang* 2017/3/3.*/ public class CatTest {@JsonProperty("cat_width")public String catWidth;@JsonProperty("cat_height")public String catHeight;public String getCatWidth() {return catWidth;}public void setCatWidth(String catWidth) {this.catWidth = catWidth;}public String getCatHeight() {return catHeight;}public void setCatHeight(String catHeight) {this.catHeight = catHeight;} }MyJsonUtil
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper;import java.io.IOException;/*** @author :taohong.ouyang* 2017/3/3.*/ public class MyJsonUtil {public String toJson(Object o){ObjectMapper mapper = new ObjectMapper();String json = null;try {json = mapper.writeValueAsString(o);} catch (JsonProcessingException e) {e.printStackTrace();}return json;}public Object toObject(String json,Class clazz){ObjectMapper mapper = new ObjectMapper();Object user = null;try {user = mapper.readValue(json, clazz);} catch (IOException e) {e.printStackTrace();}return user;} }JsonTest
public class JsonTest {public static void main(String[] args) {CatTest catTest = new CatTest();catTest.setCatHeight("height");catTest.setCatWidth("width");MyJsonUtil jsonUtil = new MyJsonUtil();String result = jsonUtil.toJson(catTest);System.out.println(result);String test = "{\"cat_width\":\"width\",\"cat_height\":\"height\"}";CatTest catTest1 = (CatTest) jsonUtil.toObject(test,CatTest.class);System.out.println(catTest1.getCatHeight() + " ======"+catTest1.getCatWidth());} }轉載于:https://my.oschina.net/ouyangtaohong/blog/850705
總結
- 上一篇: 浅谈Java中的==和equals
- 下一篇: 实用渗透工具记录