1.Javabean对象转换成String类型的JSON字符串
// 字符串数组转换 json字符串ArrayList<String> arrayList = new ArrayList<>();arrayList.add("非近距跑道");arrayList.add("近距跑道");String str = JSONObject.toJSONString(arrayList);System.out.println("字符串数组转json字符串:"+str);//简单java类转json字符串User user = new User("dmego", "123456");String UserJson = JSONObject.toJSONString(user);System.out.println("简单java类转json字符串:"+UserJson);//List<Object>转json字符串User user1 = new User("zhangsan", "123123");User user2 = new User("lisi", "321321");List<User> users = new ArrayList<User>();users.add(user1);users.add(user2);String ListUserJson = JSONObject.toJSONString(users);System.out.println("List<Object>转json字符串:"+ListUserJson);
2.String类型的JSON字符串转换成Javabean对象
// json字符串转字符串数组JSONArray jsonArray= JSONArray.parseArray(str);System.out.println("json字符串转字符串数组:"+jsonArray);user = JSON.parseObject(UserJson, User.class);System.out.println("json字符串转简单java对象:"+user.toString());users = JSON.parseArray(ListUserJson, User.class);System.out.println("json字符串转List<Object>对象:"+users.toString());
3.Json字符串转换成JSONObject对象
String jsonStr = "{\"msg\":\"ZhangSan\"}";
JSONObject jsonObject = JSONObject.parseObject(jsonStr);
4.JSON转换成Javabean对象
JSONObject.toJavaObject(JSON,Javabean.class)// 源码public static <T> T toJavaObject(JSON json, Class<T> clazz) {return TypeUtils.cast(json, clazz, ParserConfig.getGlobalInstance());}
fastjson详情 转载