fastjson与各类型的转换

参考:

https://www.cnblogs.com/ceshi2016/p/7381478.html

http://www.cnblogs.com/goody9807/p/4244862.html

 https://www.cnblogs.com/DreamDrive/p/5778959.html

https://www.cnblogs.com/janson071/p/9646678.html 多层嵌套

 

 

1、对象和JSON的转换

以Board对象为例:

// Board定义
public class Board implements Comparable<Board> {
    public String name;
    public String pinlei;
    public double gpm;
    public double ctr;
    
    public Board() {}
    
    public Board(String name, String pinlei, double gpm, double ctr) {
        this.name = name;
        this.pinlei = pinlei;
        this.gpm = gpm;
        this.ctr = ctr;
    }
    
    @Override
    public int compareTo(Board board) {           
        if(this.gpm  >= board.gpm) {
            return -1;
        }
        return 1;
    }
    
    @Override
    public String toString() {
        return name + String.valueOf(gpm) + "-";
    }
}

// Board 对象转化JSON字符串
String r_str = JSON.toJSONString(board)
System.out.println(r_str); 

// 输出结果:  {"ctr":0.1,"gpm":0.5,"name":"美白防晒霜","pinlei":"防晒霜"}

 

2、对象List和JSONArray的转换

// Board对象的list 可以直接转化到 JSONArray 
JSONArray jArray=JSON.parseArray(JSON.toJSONString(boards));

// jArray转换到JSON数组字符串
System.out.println(jArray.toJSONString();

// 输出结果: [{"ctr":0.0,"pinlei":"防晒霜3","gpm":0.8,"name":"美白防晒霜3"},{"ctr":0.0,"pinlei":"防晒霜4","gpm":0.5,"name":"美白防晒霜4"}]

 

3、字符串和JSON相互转换

/**字符串转Json对象**/
String jsonInfo = "{"ctr":0.0,"gpm":0.8,"name":"美白防晒霜3","pinlei":"防晒霜3"}";
JSONObject jsonObject = JSONObject.parseObject(jsonInfo);
/**Json对象转字符串**/
String jsonStrng = JSON.toJSONString(jsonObject);

 

4、字符串和JSON数组相互转换

// 将字符串jsonArrayStr转化为JSONArray. 
//
jsonArrayStr示例: [{"ctr":0.0,"pinlei":"防晒霜3","gpm":0.8,"name":"美白防晒霜3"},{"ctr":0.0,"pinlei":"防晒霜4","gpm":0.5,"name":"美白防晒霜4"}]
JSONArray array =  JSONArray.parseArray(jsonArrayStr));

// 将JSON数组jsonArray转化字符串
String jsonArrayStr = jsonArray.toJSONString();

 

5、map和JSON相互转换

/**map转Json对象**/
Map<String, String> map = new HashMap<String, String>();
JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(map));

/**Json对象转map**/
Map<String, Object> map2 = JSONObject.toJavaObject(jsonObject, Map.class);

 

6、map和字符串相互转换

/**map转字符串, 一般不直接Map对象使用toString()转化,而是先转换为Json对象再转字符串**/
Map<String, String> map = new HashMap<String, String>();
JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(map));
jsonObject.toString();

  // map.toString(); 不推荐

/**json字符串转map, 通过先转json再转map实现,见上**/

 

7、JSONArray和JSON遍历

// JsonArray遍历, 参考 https://www.jianshu.com/p/ca9b83ebac7b

private static void LoopJSONArray(){
        //颜色数组字符串
        String colorStr = "[{'name':'刘德华','age':28,'sex':'男'}," + 
                           "{'name':'张学友','age':29,'sex':'男'}]";
        //转化为数组
        JSONArray jsonArr = JSONArray.fromObject(colorStr); 

        for (int i = 0; i < jsonArr.size(); i++) {
            JSONObject jsonObject = jsonArr.getJSONObject(i);
            String name = jsonObject.getString("name");
            Integer age = (Integer) jsonObject.get("age");
            System.out.println("name:"+name+";age:"+age);
        }
    }

// Json遍历
JSONObject jsonObject = new JSONObject(s);
//然后用Iterator迭代器遍历取值
JSONObject jsonObject = new JSONObject(jsonString);
Iterator iterator = jsonObject.keys();
while(iterator.hasNext()){
        key = (String) iterator.next();
        value = jsonObject.getString(key);
}

 

 

 

废弃

/**字符串转Json数组并解析**/

try {

JSONArray array =  JSONArray.parseArray(line));
         String[] fields = {"lat", "lng", "poi_id", "poi_name", "poi_type", "roadidx"};
         if (null != array) {
             Iterator<Object> iter = array.iterator();
             while (iter.hasNext()) {
                 JSONObject json = (JSONObject)iter.next();
                 for (int i = 0; i < fields.length; i++) {
                     System.out.println(json.getString(fields[i]));
                 }
             }
         }

}catch (JSONException e) {
  System.err.println("json paese exception = " + jsonStr);
}

 

/**map转Json对象**/
Map<String, String> map = new HashMap<String, String>();
JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(map));
/**Json对象转map**/
Map<String, Object> map2 = JSONObject.toJavaObject(jsonObject, Map.class);


/**将List转换成JSONArray**/
List<String> list = new ArrayList<String>();
JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(list));
/**将JSONArray转换成List**/
http://www.cnblogs.com/goody9807/p/4244862.html


/**字符串转Json对象**/
String jsonInfo = "";
JSONObject jsonObject2 = JSONObject.parseObject(jsonInfo);
/**Json对象转字符串**/
String jsonStrng = JSON.toJSONString(jsonObject2);

 

/**对JSONObject中的指定字段重新赋值**/

JSONObject posJson = new JSONObject();

posJson.put("op", "in");

 

/**其它**/

public class JsonDemo {
    public static void main(String[] args) {

        //1.json字符串转换为对象
        String jsonString="{'name':'42313123','id':'2345','age':12}";
        JSONObject jsonObject = JSONObject.parseObject(jsonString);
        String id = jsonObject.getString("id");
        System.out.println(id);

        //2. JSONObject转化成自定义类对象
        PeoplePo peoplePo1 = JSONObject.parseObject(jsonString, PeoplePo.class);
        System.out.println(peoplePo1);

        //3. JSONObject转化成Map集合
        Map map = JSONObject.parseObject(jsonString, Map.class);
        System.out.println(map);

        //4. 自定义对象转化成json格式的字符串
        PeoplePo peoplePo = new PeoplePo();
        peoplePo.setId("1");
        peoplePo.setAge(11);
        peoplePo.setName("LH");
        String peopleJson = JSON.toJSONString(peoplePo);
        System.out.println(peopleJson);

        //5. String类型转化成JSONObject;
        String str = "{\"result\":\"success\",\"message\":\"成功!\"}";
        JSONObject jsonObject1 = JSONObject.parseObject(str);
        System.out.println(jsonObject1);

        //6. JSONObject转化成JSONArray的两种方式
        String str1 = "{\"result\":\"success\",\"message\":\"成功!\",\"data\":[{\"name\":\"Tom\",\"age\":\"20\"}]}";
        JSONObject jsonToArray = JSONObject.parseObject(str1);
        //方式一
        JSONArray data = jsonToArray.getJSONArray("data");
        System.out.println(data);
        //方式二
        JSONArray jsonArray = JSONArray.parseArray(jsonToArray.getString("data"));
        System.out.println(jsonArray);

        //7. jsonArray转化成JSONObject并取出其中的元素数据
        JSONObject o = (JSONObject) jsonArray.get(0);
        String name = o.getString("name");
        System.out.println(o);
        System.out.println(name);
        System.out.println(jsonArray.toString());
    }
}
//转自 https://blog.csdn.net/lh19960914/article/details/87861308
posted @ 2018-06-15 17:09  chease  阅读(2104)  评论(0编辑  收藏  举报