如何将JSON字符串转换为Java对象的列表?

时间:2017-06-16 12:34:20

标签: java json jackson jackson-databind

这是我的JSON数组: -

[ 
    {
        "firstName" : "abc",
        "lastName" : "xyz"
    }, 
    {
        "firstName" : "pqr",
        "lastName" : "str"
    } 
]

我的String对象中有这个。现在我想将它转换为Java对象并将其存储在Java对象的List中。例如在Student对象中。 我使用下面的代码将其转换为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

9 个答案:

答案 0 :(得分:36)

你要求杰克逊解析StudentList。告诉它解析一个List(学生)。由于List是通用的,因此您通常会使用TypeReference

List<Student> participantJsonList = mapper.readValue(jsonString, new TypeReference<List<Student>>(){});

答案 1 :(得分:4)

您也可以在这种情况下使用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
}

答案 2 :(得分:1)

对于任何仍在寻找答案的人:

1。将jackson-databind库添加到诸如Gradle或Maven之类的构建工具中

2。在您的代码中:

ObjectMapper mapper = new ObjectMapper();

List<Student> studentList = new ArrayList<>();

studentList = Arrays.asList(mapper.readValue(jsonStringArray, Student[].class));

答案 3 :(得分:0)

StudentList studentList = mapper.readValue(jsonString,StudentList.class);

将此更改为此

StudentList studentList = mapper.readValue(jsonString, new TypeReference<List<Student>>(){});

答案 4 :(得分:0)

我已经通过创建JSON的POJO类(Student.class)解决了这一问题,并且Main 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;
} }

答案 5 :(得分:0)

我在下面制作了一种称为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;
    }

答案 6 :(得分:0)

尝试一下。它和我一起工作。希望你也一样!

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);

答案 7 :(得分:0)

您可以使用下面的类来读取对象列表。它包含静态方法来读取具有某些特定对象类型的列表。它包含的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;
    }
}

答案 8 :(得分:0)

使用以下简单代码,无需使用任何库

String list = "your_json_string";
Gson gson = new Gson();                         
Type listType = new TypeToken<ArrayList<YourClassObject>>() {}.getType();
ArrayList<YourClassObject> users = new Gson().fromJson(list , listType);