Json jackson:无法解析json文件

时间:2014-05-30 13:03:51

标签: java json eclipse jackson

我正在尝试解析JSON文件并将其存储在列表中。我收到此错误: com.fasterxml.jackson.databind.JsonMappingException:无法从START_OBJECT标记中反序列化java.util.ArrayList的实例

这是我的JSON文件

{  "budgetList":[
    {
        "label":"Salary Tim",
        "category":"Monthly Income",  
        "real":1590,  
        "estimated":1590,  
        "date":"",  
        "month":"",  
        "year":"",  
        "type":"Income" 
    },  
    {
        "label":"Salary Tom",  
        "category":"Monthly Income",  
        "real":1540,  
        "estimated":1540,  
        "date":"",  
        "month":"",  
        "year":"",  
        "type":"Income"
    } 
 ]  
}

这是我的代码
预算:

public class Budget {
  private String label;
  private String category;
  private int real;
  private int estimated;
  private Date date;
  private int year;
  private String type;
  ....
  ....

}

我的服务:

List<Budget> budgets = objectMapper.readValue(new File("src/main/resources/json/new_exercise.json"), TypeFactory.defaultInstance().constructCollectionType(List.class,
                        Budget.class));

我哪里错了?

提前致谢。

找到答案

代码是

ObjectMapper objectMapper = new ObjectMapper();
List<Budget> budgets = null; 
JsonNode node = objectMapper.readTree(new File("src/main/resources/json/new_exercise.json"));
            node = node.get("budgetList");
TypeReference<List<Budget>> typeRef = new TypeReference<List<Budget>>(){};
budgets = objectMapper.readValue(node.traverse(), typeRef);

1 个答案:

答案 0 :(得分:0)

你可以使用GSON库吗?非常简单

  

Reader reader = new InputStreamReader(new   的FileInputStream( “/选择/ file.json”));
  Gson gson = gsonBuilder.create();
  列表listBudget = gson.fromJson(读者,新   TypeToken&gt;(){}。getType());

我认为唯一的问题是当Date和整数解析器为空时。但您可以注册适配器,如:

  GsonBuilder gsonBuilder = new GsonBuilder();
          gsonBuilder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
      DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");

      public Date deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context)
              throws JsonParseException {
          try {
              return df.parse(json.getAsString());
          } catch (ParseException e) {
              return null;
          }
      }
  });
     

Reader reader = new InputStreamReader(new   的FileInputStream( “/选择/ file.json”));   Gson gson = gsonBuilder.create();
  列表listBudget = gson.fromJson(读者,新   TypeToken&gt;(){}。getType());

它对你有用吗?不要忘记验证你json。 “