依赖fastjson

一、String

1.String转JSONObject

JSONObject jsonObject = JSON.parseObject(String)

2.String转JSONArray

JSONArray jsonArray = JSONArray.parseArray(String)

  1. String jsonMessage = "[{\"语文\":\"88\"},{\"数学\":\"78\"},{\"计算机\":\"98\"}]";
  2. JSONArray jsonArray = JSONArray.parseArray(jsonMessage);
  3. [{"语文":"88"},{"数学":"78"},{"计算机":"98"}]

3.String转Object

Obj obj = JSONObject.parseObject(String,Obj.class)

  1. People people = new People();
  2. people.setName("张三");
  3. people.setAge(15);
  4. people.setHeight(12.5F);
  5. people.setDesc("法外狂徒");
  6. String string = JSONObject.toJSONString(people);
  7. People people1 = JSONObject.parseObject(string, People.class);

4.String转List

  • 格式为 “1,2,3”;
  • 格式为 [{“uid”:“1”,“userName”:“小明”},{“uid”:“2”,“userName”:“小红”}]

格式一:String uid=”1,2,3”;
①转为List uids={1,2,3}

  1. List<Long> uids=Arrays.stream(uid.split(",")).map(s->Long.parseLong(s.trim())).collect(Collectors.toList())

②转为List uids={“1”,”2”,”3”}

  1. List<String> uids=Arrays.asList(uid.split(","));

格式二:String user=”[{\”uid\”:\”1\”,\”userName\”:\”小明\”},{\”uid\”:\”2\”,\”userName\”:\”小红\”}]”;
转为List

  1. List<User> userList=JSONArray.parseArray(user,User.class);

5.String转Map

①split(“,”),遍历再split(“:”) map.put()

  1. public static Map<String, String> getStringToMap(String str) {
  2. // 判断str是否有值
  3. if (null == str || "".equals(str)) {
  4. return null;
  5. }
  6. // 根据&截取
  7. String[] strings = str.split(",");
  8. // 设置HashMap长度
  9. int mapLength = strings.length;
  10. Map<String, String> map = new HashMap<>(mapLength);
  11. // 循环加入map集合
  12. for (String string : strings) {
  13. // 截取一组字符串
  14. String[] strArray = string.split(":");
  15. // strArray[0]为KEY strArray[1]为值
  16. map.put(strArray[0], strArray[1]);
  17. }
  18. return map;
  19. }

②转jsonObject,遍历jsonObject,相当于两个map操作;

  1. JSONObject user = resJson.getJSONObject("user");
  2. Map<String, Object> userMap = new HashMap<>();
  3. //循环转换
  4. for (Map.Entry<String, Object> entry : user.entrySet()) {
  5. userMap.put(entry.getKey(), entry.getValue());
  6. }

二、JSONObject

1.jsonObject转