依赖fastjson
一、String
1.String转JSONObject
JSONObject jsonObject = JSON.parseObject(String)
2.String转JSONArray
JSONArray jsonArray = JSONArray.parseArray(String)
String jsonMessage = "[{\"语文\":\"88\"},{\"数学\":\"78\"},{\"计算机\":\"98\"}]";
JSONArray jsonArray = JSONArray.parseArray(jsonMessage);
[{"语文":"88"},{"数学":"78"},{"计算机":"98"}]
3.String转Object
Obj obj = JSONObject.parseObject(String,Obj.class)
People people = new People();
people.setName("张三");
people.setAge(15);
people.setHeight(12.5F);
people.setDesc("法外狂徒");
String string = JSONObject.toJSONString(people);
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
List<Long> uids=Arrays.stream(uid.split(",")).map(s->Long.parseLong(s.trim())).collect(Collectors.toList())
②转为List
List<String> uids=Arrays.asList(uid.split(","));
格式二:String user=”[{\”uid\”:\”1\”,\”userName\”:\”小明\”},{\”uid\”:\”2\”,\”userName\”:\”小红\”}]”;
转为List
List<User> userList=JSONArray.parseArray(user,User.class);
5.String转Map
①split(“,”),遍历再split(“:”) map.put()
public static Map<String, String> getStringToMap(String str) {
// 判断str是否有值
if (null == str || "".equals(str)) {
return null;
}
// 根据&截取
String[] strings = str.split(",");
// 设置HashMap长度
int mapLength = strings.length;
Map<String, String> map = new HashMap<>(mapLength);
// 循环加入map集合
for (String string : strings) {
// 截取一组字符串
String[] strArray = string.split(":");
// strArray[0]为KEY strArray[1]为值
map.put(strArray[0], strArray[1]);
}
return map;
}
②转jsonObject,遍历jsonObject,相当于两个map操作;
JSONObject user = resJson.getJSONObject("user");
Map<String, Object> userMap = new HashMap<>();
//循环转换
for (Map.Entry<String, Object> entry : user.entrySet()) {
userMap.put(entry.getKey(), entry.getValue());
}
二、JSONObject
1.jsonObject转