如何使用Jackson来反序列化对象数组


779

杰克逊的数据绑定的文档表明,杰克逊支持deserialising“所有支持类型的数组”,但我不能找出确切的语法这一点。

对于单个对象,我可以这样做:

//json input
{
    "id" : "junk",
    "stuff" : "things"
}

//Java
MyClass instance = objectMapper.readValue(json, MyClass.class);

现在,对于数组,我想这样做:

//json input
[{
    "id" : "junk",
    "stuff" : "things"
},
{
    "id" : "spam",
    "stuff" : "eggs"
}]

//Java
List<MyClass> entries = ?

有人知道是否有不可思议的命令吗?如果没有,那么解决方案是什么?


2
我更喜欢Google的GSON库来处理JSON。值得一看的是,如果您还没有尝试过,那么使用它非常容易且直观。
Jesse Webb

11
FWIW使用Gson解决此特定问题的可能解决方案几乎与使用Jackson的数据绑定API的解决方案相同。
程序员布鲁斯(Bruce)

17
Gweebz-也许您想解释一下为什么您觉得GSON是更好的选择(与Jackson相比)?
StaxMan 2011年

Answers:


1653

首先创建一个映射器:

import com.fasterxml.jackson.databind.ObjectMapper;// in play 2.3
ObjectMapper mapper = new ObjectMapper();

作为数组:

MyClass[] myObjects = mapper.readValue(json, MyClass[].class);

作为列表:

List<MyClass> myObjects = mapper.readValue(jsonInput, new TypeReference<List<MyClass>>(){});

指定列表类型的另一种方法:

List<MyClass> myObjects = mapper.readValue(jsonInput, mapper.getTypeFactory().constructCollectionType(List.class, MyClass.class));

43
需要特别注意的是,如果在解析时遇到诸如此类的错误,JsonMappingException: No suitable constructor found for type则意味着您需要向类中添加默认构造函数,并添加一个私有的无参数构造函数为我修复了该问题。
SyntaxRules 2013年

12
如果您有显式构造函数,则需要@SyntaxRules添加显式构造函数-否则,编译器会自动创建公共的“空”构造函数。好点子。另一个常见的问题是内部类必须是static-否则它们永远不会具有零参数构造函数。
StaxMan

244
顺便说一句,List<MyClass> myObjects = Arrays.asList(mapper.readValue(json, MyClass[].class))比TypeRefence的处理速度快10倍。

5
我正在寻找通用类型的版本。
Stephane 2014年

1
@EugeneTskhovrebov您的方式最适合内联。其他要求强制转换或声明。我建议将其添加为自己的答案,以帮助突出显示它,并给您代表。
Erik B

190

Eugene Tskhovrebov

List<MyClass> myObjects = Arrays.asList(mapper.readValue(json, MyClass[].class))

这个解决方案似乎对我来说是最好的


对于使用Java,Lotus Domino和Agent的人来说,这是必须走的路。我尝试了其他一些解决方案,但总能得到ResourceNotFoundException
John

此解决方案可能需要在上述答案的注释中添加SyntaxRules,因为这对我来说是必需的。我只是想补充一点,以免丢失。
罗布

2
Arrays.asList(Json.fromJson(json.get("fieldName"), MyClass[].class))
Al-Mothafar

3
List<MyClass> myObjects = Arrays.asList(mapper.treeToValue(jsonNode.get("fieldName"), MyClass[].class))
Collin Krawll,

@CollinKrawll objectmapper.treetovalue做什么?
Eswar

35

对于通用实现:

public static <T> List<T> parseJsonArray(String json,
                                         Class<T> classOnWhichArrayIsDefined) 
                                         throws IOException, ClassNotFoundException {
   ObjectMapper mapper = new ObjectMapper();
   Class<T[]> arrayClass = (Class<T[]>) Class.forName("[L" + classOnWhichArrayIsDefined.getName() + ";");
   T[] objects = mapper.readValue(json, arrayClass);
   return Arrays.asList(objects);
}

4
Class <T []>的不错的构造。没看过 您在哪里找到有关此信息?
Roeland Van Heddegem

11

首先创建一个线程安全的ObjectReader实例。

ObjectMapper objectMapper = new ObjectMapper();
ObjectReader objectReader = objectMapper.reader().forType(new TypeReference<List<MyClass>>(){});

然后使用它:

List<MyClass> result = objectReader.readValue(inputStream);

正是我想要的,谢谢
独自一人,

我们确实得到了-com.fasterxml.jackson.databind.JsonMappingException:无法从START_OBJECT令牌中反序列化java.util.ArrayList的实例,位于[Source:java.io.FileInputStream@33fec21; 行:1,列:1]
Dinesh Kumar

7
try {
    ObjectMapper mapper = new ObjectMapper();
    JsonFactory f = new JsonFactory();
    List<User> lstUser = null;
    JsonParser jp = f.createJsonParser(new File("C:\\maven\\user.json"));
    TypeReference<List<User>> tRef = new TypeReference<List<User>>() {};
    lstUser = mapper.readValue(jp, tRef);
    for (User user : lstUser) {
        System.out.println(user.toString());
    }

} catch (JsonGenerationException e) {
    e.printStackTrace();
} catch (JsonMappingException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

3

这是一个可以转换json2object或Object2json的实用程序,无论您的pojo(实体T)如何

import java.io.IOException;
import java.io.StringWriter;
import java.util.List;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

/**
 * 
 * @author TIAGO.MEDICI
 * 
 */
public class JsonUtils {

    public static boolean isJSONValid(String jsonInString) {
        try {
            final ObjectMapper mapper = new ObjectMapper();
            mapper.readTree(jsonInString);
            return true;
        } catch (IOException e) {
            return false;
        }
    }

    public static String serializeAsJsonString(Object object) throws JsonGenerationException, JsonMappingException, IOException {
        ObjectMapper objMapper = new ObjectMapper();
        objMapper.enable(SerializationFeature.INDENT_OUTPUT);
        objMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
        StringWriter sw = new StringWriter();
        objMapper.writeValue(sw, object);
        return sw.toString();
    }

    public static String serializeAsJsonString(Object object, boolean indent) throws JsonGenerationException, JsonMappingException, IOException {
        ObjectMapper objMapper = new ObjectMapper();
        if (indent == true) {
            objMapper.enable(SerializationFeature.INDENT_OUTPUT);
            objMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
        }

        StringWriter stringWriter = new StringWriter();
        objMapper.writeValue(stringWriter, object);
        return stringWriter.toString();
    }

    public static <T> T jsonStringToObject(String content, Class<T> clazz) throws JsonParseException, JsonMappingException, IOException {
        T obj = null;
        ObjectMapper objMapper = new ObjectMapper();
        obj = objMapper.readValue(content, clazz);
        return obj;
    }

    @SuppressWarnings("rawtypes")
    public static <T> T jsonStringToObjectArray(String content) throws JsonParseException, JsonMappingException, IOException {
        T obj = null;
        ObjectMapper mapper = new ObjectMapper();
        obj = mapper.readValue(content, new TypeReference<List>() {
        });
        return obj;
    }

    public static <T> T jsonStringToObjectArray(String content, Class<T> clazz) throws JsonParseException, JsonMappingException, IOException {
        T obj = null;
        ObjectMapper mapper = new ObjectMapper();
        mapper = new ObjectMapper().configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
        obj = mapper.readValue(content, mapper.getTypeFactory().constructCollectionType(List.class, clazz));
        return obj;
    }

0

您还可以创建一个扩展了的类ArrayList

public static class MyList extends ArrayList<Myclass> {}

然后像这样使用它:

List<MyClass> list = objectMapper.readValue(json, MyList.class);
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.