简体   繁体   中英

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.

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:

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 :

{'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 . Your json value contains a JSON object. A List type can only be deserialized from a JSON array.

Just use

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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