JSON 转换 汇总

  本文汇总JSON和各种数据的转换方法,使用的是 com.alibaba.fastjson.JSONObject。

 

一,String - > JSON

String json = "{\"name\":\"xiaobai\",\"password\":\"123123\"}";
JSONObject json_test = JSONObject.parseObject(json);
结果:{"password":"123123","name":"xiaobai"}

二,JSON - > String

String s = jsonObect.toString();
结果:{"password":"123123","name":"xiaobai"}

三,JSON - > JAVA实体类

String userStr = "{\"userName\":\"小黑\",\"mobile\":\"15600000000\"}";
UserInfo retUser = JSONObject.parseObject(userStr, UserInfo.class);
结果:UserInfo(userName=小黑, mobile=15600000000)

四,JAVA实体类 - > JSON

UserInfo userInfo = new UserInfo();
userInfo.setUserName("小白");
userInfo.setMobile("15600000000");
String json = JSONObject.toJSONString(userInfo);
结果:{"mobile":"15600000000","userName":"小白"}

五,List<Entity> - > JSON

List<UserInfo> uList = new ArrayList<>();
UserInfo u1 = new UserInfo();
u1.setUserName("小白");
u1.setMobile("15600000000");
UserInfo u2 = new UserInfo();
u2.setUserName("小黑");
u2.setMobile("15500000000");
uList.add(u1);
uList.add(u2);
String json = JSON.toJSONString(uList);
结果:[{"mobile":"15600000000","userName":"小白"},{"mobile":"15500000000","userName":"小黑"}]

六,JSON - > List<Entity> 

List<UserInfo> uList = new ArrayList<>();
UserInfo u1 = new UserInfo();
u1.setUserName("小白");
u1.setMobile("15600000000");
UserInfo u2 = new UserInfo();
u2.setUserName("小黑");
u2.setMobile("15500000000");
uList.add(u1);
uList.add(u2);
String json = JSON.toJSONString(uList); 
List<UserInfo> ts = JSONArray.parseArray(json, UserInfo.class);
结果:[UserInfo(userName=小白, mobile=15600000000), UserInfo(userName=小黑, mobile=15500000000)]

第二种方式:
String jsons = "[{'city': '中国大陆','code': '+86'},{'city': '中国香港','code': '+852'}"
JSONArray jsonArray = JSONArray.parseArray(jsons);
List<你的javabean> javabeanList = jsonArray.toJavaList(你的javaBean.class);

七,MAP - > JSON

Map<String,Object> map = new HashMap<>();
map.put("code",1);
List<UserInfo> uList = new ArrayList<>();
UserInfo u1 = new UserInfo();
u1.setUserName("小白");
u1.setMobile("15600000000");
UserInfo u2 = new UserInfo();
u2.setUserName("小黑");
u2.setMobile("15500000000");
uList.add(u1);
uList.add(u2);
map.put("userList",uList);

1.alibaba String mapJson
= JSONObject.toJSONString(map);
2.json-lib
JSONObject jsonObject = JSONObject.fromObject(map);
String mapJson = jsonObject.toString();
3.google
String mapJson = new Gson().toJson(map); 
结果:{"code":1,"userList":[{"mobile":"15600000000","userName":"小白"},{"mobile":"15500000000","userName":"小黑"}]}

八,JSON - > MAP

Map<String,Object> map = new HashMap<>();
map.put("code",1);
List<UserInfo> uList = new ArrayList<>();
UserInfo u1 = new UserInfo();
u1.setUserName("小白");
u1.setMobile("15600000000");
UserInfo u2 = new UserInfo();
u2.setUserName("小黑");
u2.setMobile("15500000000");
uList.add(u1);
uList.add(u2);
map.put("userList",uList);

//JSON to Map
String mapJson = JSONObject.toJSONString(map);
Map maps = (Map)JSON.parse(mapJson);
结果:{"code":1,"userList":[{"mobile":"15600000000","userName":"小白"},{"mobile":"15500000000","userName":"小黑"}]}

//JSON to List;从JSON字符串中取某一个对象
JSONObject jsonObject = JSONObject.parseObject(mapJson);
String str = String.valueOf(jsonObject.get("userList"));
List<UserInfo> retList = JSONArray.parseArray(str, UserInfo.class);
结果:[UserInfo(userName=小白, mobile=15600000000), UserInfo(userName=小黑, mobile=15500000000)]

九,JSON工具类

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author xb
 * @description JSON 工具类
 * @date 2020/11/26
 */
@Component
public class JSONUtils {

    // 定义jackson对象
    private static final ObjectMapper MAPPER = new ObjectMapper();

    /**
     * @description: List<T> 转 json
     * @param ts
     * @return: java.lang.String
     * @author: xb
     * @Date: 2020/11/26 10:52
     */
    public static <T> String listToJson(List<T> ts) {
        String jsons = JSON.toJSONString(ts);
        return jsons;
    }

    /**
     * @description: json 转 List<T>
     * @param jsonString
     * @param clazz
     * @return: java.util.List<T>
     * @author: xb
     * @Date: 2020/11/26 10:52
     */
    public static <T> List<T> jsonToList(String jsonString, Class<T> clazz) {
        @SuppressWarnings("unchecked")
        List<T> ts = JSONArray.parseArray(jsonString, clazz);
        return ts;
    }

    /**
     * @description: 将对象转换成json字符串。
     * @param data
     * @return: java.lang.String
     * @author: xb
     * @Date: 2020/11/26 11:32
     */
    public static String objectToJson(Object data) {
        try {
            String string = MAPPER.writeValueAsString(data);
            return string;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * @description: 将json结果集转化为对象
     * @param jsonData
     * @param beanType
     * @return: T
     * @author: xb
     * @Date: 2020/11/26 11:32
     */
    public static <T> T jsonToPojo(String jsonData, Class<T> beanType) {
        MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        try {
            T t = MAPPER.readValue(jsonData, beanType);
            return t;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}

 

posted @ 2020-11-26 11:34  追太阳的小码妹  阅读(369)  评论(0编辑  收藏  举报