maven依赖
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.28</version>
</dependency>
Gson
String personJsonInfo={"":""};
//String personJsonInfo= "{\"a\":\"1\",\"b\":{\"c\":\"2\",\"d\":\"[3,4]\"}}";
Gson gson = new Gson();
//Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();//排除掉bean中没有Expose注解的属性
Person person = gson.fromJson(personJsonInfo, Person.class);
JsonArray
String personJsonInfo= "[{id:'1',name:'aa'},{id:'2',name:'bb'},{id:'3',name:'cc'},{id:'4',name:'dd'}]";
JSONArray jsonArray = JSONArray.fromObject(personJsonInfo);
person =new ObjectMapper().readValue(jsonArray.getString(i), Person.class);
或JSONObject json = jsonArray.getJSONObject(i);
//json.get("id")
//jsonArray 转 list
List<Person> personList = JSONArray.toList(jsonArray, new Person(), new JsonConfig());
fastjson
使用fastjson要注意要转换的类必须有默认的无参构造方法。
String str = JSON.toJSONString(product));
Product product = JSON.parseObject(str, Product.class);
JSONObject jsonObject = JSONObject.fromObject(data);
//按缺省排序 JSONObject jsonObject = JSONObject.parseObject(personJsonInfo,JSONObject.class, Feature.OrderedField);
JSONObject orderInfoJson = null;
if (jsonObject.has("orderInfo")) {
orderInfoJson = jsonObject.getJSONObject("orderInfo");
}
//生成json
public static String createJsonString(String key, Object value) {
JSONObject jsonObject = new JSONObject();
jsonObject.put(key, value);
//删除 jsonObject.remove(key);
return jsonObject.toString();
}
注意:
1、为了避免使用Gson时遇到locale影响Date格式的问题,如下
Caused by: java.text.ParseException: Failed to parse date ["2017-12-21 11:30:08']: Invalid time zone indicator ' '
则使用GsonBuilder来创建Gson对象,在创建过程中调用GsonBuilder.setDateFormat(String)指定一个固定的格式即可。例如:
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create(); //按照 yyyy-MM-dd HH:mm:ss格式化。
2、Gson因无法解析时间戳格式,而出现类似以下的异常
java.text.ParseException: Failed to parse date ["1302828677828']: Invalid time zone indicator '7' (at offset 0)
则需要设置转换适配器如下
// Creates the json object which will manage the information received
GsonBuilder builder = new GsonBuilder();
// Register an adapter to manage the date types as long values
builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
return new Date(json.getAsJsonPrimitive().getAsLong());
}
});
Gson gson = builder.create();