alibaba.fastjson.JSONObject 解析

public class JsonDemo {json

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);get


//2. JSONObject轉化成自定義類對象class

  PeoplePo peoplePo1 = JSONObject.parseObject(jsonString, PeoplePo.class);
  System.out.println(peoplePo1);map

 

//3. JSONObject轉化成Map集合數據

  Map map = JSONObject.parseObject(jsonString, Map.class);
  System.out.println(map);static

 

//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());

      }}

相關文章
相關標籤/搜索