简体   繁体   English

Java中的JSON字符串解析

[英]JSON String parsing in java

Im passing a string to a method and i need to deserialize it into an object but i keep running into a JSON Mapping exception. 我将字符串传递给方法,我需要将其反序列化为对象,但我一直遇到JSON映射异常。

private static final ObjectMapper mapper = new ObjectMapper();

public ArrayList<Double> parseVector(String json){
    Vector vector = new Vector();
    try {
        vector = mapper.readValue(json, TypeFactory.collectionType(ArrayList.class, Vector.class));
    } catch ETC ........ 

It should also be noted that Vector is an inner class and is setup as follows: 还应注意,Vector是一个内部类,其设置如下:

static class Vector{
    @JsonProperty("P")
    public Double performance;
    @JsonProperty("M")
    public Double margin;
    @JsonProperty("I")
    public Double pace;
}

for this example the value of json is : 对于此示例,json的值为:

{'P':8,'M':2,'I':0} 

Im getting this exception : 我得到这个异常:

JSONDeserializer : getVectorMap()   JsonMappingException : 
org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token
 at [Source: java.io.StringReader@77d65595; line: 1, column: 1]

Can anyone give me some insight into this? 谁能给我一些见识?

Jackson cannot deserialize non-static inner classes. 杰克逊无法反序列化非静态内部类。 This constraint is there because there is no general way to instantiate such classes since there is no default constructor for the inner class. 之所以存在该约束,是因为没有内部类的默认构造函数,因此没有通用的方法来实例化此类。 Serialization works fine, however. 但是,序列化工作正常。

This post provides a more detailed reasoning: 这篇文章提供了更详细的推理:

Note that an inner class can access all member variables of the outer class. 请注意,内部类可以访问外部类的所有成员变量。 When we write the following code 当我们编写以下代码时

public class Outer {

    // non-static
    class Inner {

    }
}

the compiler generates something akin to 编译器生成类似于

public class Outer { ... }

class Outer$Inner {
    private final Outer parent;

    Outer$Inner(Outer p) {
        parent = p;
    }
}

Your new error comes from the fact that 您的新错误来自以下事实:

vector = mapper.readValue(json, TypeFactory.collectionType(ArrayList.class, Vector.class));

tells Jackson to deserialize a ArrayList<Vector> from the json . 告诉Jackson从json反序列化ArrayList<Vector> Your json value contains a JSON object. 您的json值包含一个JSON对象。 A List type can only be deserialized from a JSON array. 只能从JSON数组反序列化List类型。

Just use 只需使用

vector = mapper.readValue(json, Vector.class);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM