Gson反序列化不能正常工作

时间:2014-07-08 14:58:59

标签: java json list mapping deserialization

我有一个jsonarray格式如下:

String jsonArray = {"myList":[{"code":"01","price":"2,3", "date":"21/12/2014"},{"code":"02","price":"3,4", "date":"26/12/2014"}]}

Mylist类是:

public class MyList {
    private String code;
    private String price;
    private String date;

    //..getter and setter
}

我的非工作" deserializator"如下:

ObjectMapper objectMapper = new ObjectMapper();
List<MyList> list = new ObjectMapper().readValue(jsonArray, new TypeReference<List<MyList>>() { });

捕获以下异常:

       org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token

我该如何解决? 提前谢谢!

1 个答案:

答案 0 :(得分:0)

这是我使用Gson自己的工作解决方案:

String jsonArray = {"myList":[{"code":"01","price":"2,3", "date":"21/12/2014"},{"code":"02","price":"3,4", "date":"26/12/2014"}]}

Gson gson = new Gson();
JsonParser parser = new JsonParser();

List<MyList> list = new ArrayList<MyList>();
try {
    JsonArray jArray = (JsonArray) parser.parse(jsonArray).getAsJsonObject().get("myList");

    for (JsonElement jObj : jArray) {
            MyList item = gson.fromJson( jObj , MyList.class);
            list.add(item);
    }

    } catch (Exception e) {
        e.printStackTrace();
    }

希望它对其他用户有用!