![](/img/trans.png)
[英]Convert JSON to Map<String, List<Object>> in java
[英]How to convert JSON string into List of Java object?
這是我的 JSON 數組:-
[
{
"firstName" : "abc",
"lastName" : "xyz"
},
{
"firstName" : "pqr",
"lastName" : "str"
}
]
我的 String 對象中有這個。 現在我想將它轉換為 Java 對象並將其存儲在 Java 對象列表中。 例如在學生對象中。 我正在使用下面的代碼將其轉換為 Java 對象列表:-
ObjectMapper mapper = new ObjectMapper();
StudentList studentList = mapper.readValue(jsonString, StudentList.class);
我的列表類是:-
public class StudentList {
private List<Student> participantList = new ArrayList<Student>();
//getters and setters
}
我的學生對象是:-
class Student {
String firstName;
String lastName;
//getters and setters
}
我在這里錯過了什么嗎? 我遇到了以下異常:-
Exception : com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of com.aa.Student out of START_ARRAY token
您要求傑克遜解析StudentList
。 告訴它解析一個List
(學生)。 由於List
是通用的,您通常會使用TypeReference
List<Student> participantJsonList = mapper.readValue(jsonString, new TypeReference<List<Student>>(){});
你也可以在這個場景中使用 Gson。
Gson gson = new Gson();
NameList nameList = gson.fromJson(data, NameList.class);
List<Name> list = nameList.getList();
您的 NameList 類可能如下所示:
class NameList{
List<Name> list;
//getter and setter
}
對於任何正在尋找答案的人:
1.將jackson-databind
庫添加到您的構建工具中,例如 Gradle 或 Maven
2.在你的代碼中:
ObjectMapper mapper = new ObjectMapper();
List<Student> studentList = new ArrayList<>();
studentList = Arrays.asList(mapper.readValue(jsonStringArray, Student[].class));
您可以使用下面的類來讀取對象列表。 它包含靜態方法來讀取具有某些特定對象類型的列表。 它包含 Jdk8Module 更改,也提供了新的時間類支持。 它是一個干凈和通用的類。
List<Student> students = JsonMapper.readList(jsonString, Student.class);
通用 JsonMapper 類:
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import java.io.IOException;
import java.util.*;
import java.util.Collection;
public class JsonMapper {
public static <T> List<T> readList(String str, Class<T> type) {
return readList(str, ArrayList.class, type);
}
public static <T> List<T> readList(String str, Class<? extends Collection> type, Class<T> elementType) {
final ObjectMapper mapper = newMapper();
try {
return mapper.readValue(str, mapper.getTypeFactory().constructCollectionType(type, elementType));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static ObjectMapper newMapper() {
final ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.registerModule(new JavaTimeModule());
mapper.registerModule(new Jdk8Module());
return mapper;
}
}
我在下面jsonArrayToObjectList
了一個方法來執行此操作,稱為jsonArrayToObjectList
。 它是一個方便的靜態類,它將采用文件名,並且該文件包含一個 JSON 格式的數組。
List<Items> items = jsonArrayToObjectList(
"domain/ItemsArray.json", Item.class);
public static <T> List<T> jsonArrayToObjectList(String jsonFileName, Class<T> tClass) throws IOException {
ObjectMapper mapper = new ObjectMapper();
final File file = ResourceUtils.getFile("classpath:" + jsonFileName);
CollectionType listType = mapper.getTypeFactory()
.constructCollectionType(ArrayList.class, tClass);
List<T> ts = mapper.readValue(file, listType);
return ts;
}
StudentList studentList = mapper.readValue(jsonString,StudentList.class);
把這個改成這個
StudentList studentList = mapper.readValue(jsonString, new TypeReference<List<Student>>(){});
我通過創建 JSON 的 POJO 類 (Student.class) 解決了這個問題,主類用於從問題中的 JSON 讀取值。
**Main Class**
public static void main(String[] args) throws JsonParseException,
JsonMappingException, IOException {
String jsonStr = "[ \r\n" + " {\r\n" + " \"firstName\" : \"abc\",\r\n"
+ " \"lastName\" : \"xyz\"\r\n" + " }, \r\n" + " {\r\n"
+ " \"firstName\" : \"pqr\",\r\n" + " \"lastName\" : \"str\"\r\n" + " } \r\n" + "]";
ObjectMapper mapper = new ObjectMapper();
List<Student> details = mapper.readValue(jsonStr, new
TypeReference<List<Student>>() { });
for (Student itr : details) {
System.out.println("Value for getFirstName is: " +
itr.getFirstName());
System.out.println("Value for getLastName is: " +
itr.getLastName());
}
}
**RESULT:**
Value for getFirstName is: abc
Value for getLastName is: xyz
Value for getFirstName is: pqr
Value for getLastName is: str
**Student.class:**
public class Student {
private String lastName;
private String firstName;
public String getLastName() {
return lastName;
}
public String getFirstName() {
return firstName;
} }
試試這個。 它和我一起工作。 希望你也是!
List<YOUR_OBJECT> testList = new ArrayList<>(); testList.add(test1); Gson gson = new Gson(); String json = gson.toJson(testList); Type type = new TypeToken<ArrayList<YOUR_OBJECT>>(){}.getType(); ArrayList<YOUR_OBJECT> array = gson.fromJson(json, type);
最安全的方法是通過JsonParser.parseString(jsonString).getAsJsonArray()
遍歷 json 數組,並通過檢查jsonObject.has("key")
一個一個地解析它的元素。
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import lombok.Data;
@Data
class Foo {
String bar;
Double tar;
}
JsonArray jsonArray = JsonParser.parseString(jsonString).getAsJsonArray();
List<Foo> objects = new ArrayList<>();
jsonArray.forEach(jsonElement -> {
objectList.add(JsonToObject(jsonElement.getAsJsonObject()));
});
Foo parseJsonToFoo(JsonObject jsonObject) {
Foo foo = new Foo();
if (jsonObject.has("bar")) {
String data = jsonObject.get("bar").getAsString();
foo.setBar(data);
}
if (jsonObject.has("tar")) {
Double data = jsonObject.get("tar").getAsDouble();
foo.setTar(data);
}
return foo;
}
使用下面的簡單代碼,無需使用任何庫
String list = "your_json_string";
Gson gson = new Gson();
Type listType = new TypeToken<ArrayList<YourClassObject>>() {}.getType();
ArrayList<YourClassObject> users = new Gson().fromJson(list , listType);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.