简体   繁体   中英

Json jackson : can't parse a json a file

I m trying to parse a JSON file and store it in an list. I m getting this error : com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token

Here is my JSON file

{  "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"
    } 
 ]  
}

Here is my code
Budget :

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

}

My service :

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

Where am I wrong?

Thanks in advance.

ANSWER FOUND

Code is

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);

can you, use GSON library? Is very simple

Reader reader = new InputStreamReader(new FileInputStream("/opt/file.json"));
Gson gson = gsonBuilder.create();
List listBudget = gson.fromJson(reader, new TypeToken>() {}.getType());

I think that the only problem is when Date and integer parser when is empty. but you can register adapters like:

  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("/opt/file.json")); Gson gson = gsonBuilder.create();
List listBudget = gson.fromJson(reader, new TypeToken>() {}.getType());

It works for you?, and dont forget to validate you json. "

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