gson&&fastjson

来源:互联网 发布:办公室网络综合布线 编辑:程序博客网 时间:2024/06/15 19:52

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={"":""};Gson gson = new Gson();//Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();//排除掉bean中没有Expose注解的属性Person person = gson.fromJson(personJsonInfo, Person.class);

JsonArray

String personJsonInfo=[{no:'a',name:'aa'},{no:'b',name:'bb'},{no:'c',name:'cc'},{no:'d',name:'dd'}];JSONArray jsonArray = JSONArray.fromObject(personJsonInfo);person =new ObjectMapper().readValue(jsonArray.getString(i), Person.class);或JSONObject json = jsonArray.getJSONObject(i); //json.get("no")    
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");}
//生成jsonpublic 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();
原创粉丝点击