package com.kry.xr.Test; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.eebbk.pointreadOnline.app.util.JsonUtils; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.type.CollectionType; import com.kry.xr.entity.UserLog; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class Json { public static void main(String[] args) { String resultData= "[{\"userid\":19,\"username\":5,\"state\":9},{\"userid\":20,\"username\":6,\"state\":9}]"; String resultData1= "[{\"userid\":19,\"username\":5},{\"userid\":20,\"username\":6}]"; // JSONObject jsonObject=JSONObject.parseObject(resultData); string 转list //1 JSONArray list =(JSONArray)JSONArray.parseArray(resultData); List<UserLog> list1 = JSONObject.parseArray(list.toJSONString(), UserLog.class); //2 JSONArray list2 =(JSONArray)JSONArray.parseArray(resultData1); List<UserLogTest> list3 = JSONObject.parseArray(list2.toJSONString(), UserLogTest.class); //3 List<UserLog> UserLogList = jsonStr2List(resultData1, UserLog.class); Integer ap=1; //list转string String resultString=obj2JsonStr(UserLogList);
System.out.println(resultString); } public static <T> List<T> jsonStr2List(String jsonStr, Class<T> elementClass) { List<T> resultList = null; ObjectMapper objectMapper = new ObjectMapper(); CollectionType collectionType = objectMapper.getTypeFactory().constructCollectionType(ArrayList.class, elementClass); try { resultList = objectMapper.readValue(jsonStr, collectionType); } catch (RuntimeException e) { System.out.println("json字符串转List对象发生异常!"+ e); } catch (IOException e) { System.out.println("json字符串转List对象发生异常!"+ e); } return resultList; } public static String obj2JsonStr(Object obj) { ObjectMapper objectMapper = new ObjectMapper(); String result = null; try { // 允许反斜杆等字符 objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true); // 允许单引号 objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); result = objectMapper.writeValueAsString(obj); } catch (IOException e) { System.out.println("java对象转json字符串发生异常!"+e); } return result; } }
-----------------------使用@Data
import lombok.Builder;
import lombok.Data;
import lombok.experimental.Accessors;
@Data
@Accessors(chain = true)
@Builder
public class UserLog {
private String username;
private String userid;
private String state;
public UserLog(String username,String userid,String state){
this.username=username;
this.userid=userid;
this.state=state;
}
public UserLog(){
}
}