Converting JSON to Java object using Gson

前端 未结 2 511
[愿得一人]
[愿得一人] 2021-02-06 11:25

I am trying to convert JSON string to simple java object but it is returning null. Below are the class details.

JSON String:

   {\"menu\": 
    {\"id\":          


        
相关标签:
2条回答
  • 2021-02-06 11:31

    Your JSON is an object with a field menu.

    If you add the same in your Java it works:

    class MenuWrapper {
        Menu menu;
        public Menu getMenu() { return menu; }
        public void setMenu(Menu m) { menu = m; }
    }
    

    And an example:

    public static void main(String[] args) {
        String json =  "{\"menu\": {\"id\": \"file\", \"value\": \"File\"} }";
    
        Gson gson = new Gson();
        MenuWrapper m = gson.fromJson(json, MenuWrapper.class);
        System.out.println(m.getMenu().getId());
        System.out.println(m.getMenu().getValue());
    
    }
    

    It will print:

    file
    File
    

    And your JSON: {"menu": {"id": "file", "value": "File", } } has an error, it has an extra comma. It should be:

    {"menu": {"id": "file", "value": "File" } }
    
    0 讨论(0)
  • 2021-02-06 11:36

    What I have found helpful with Gson is to create an an instance of the class, call toJson() on it and compare the generated string with the string I am trying to parse.

    0 讨论(0)
提交回复
热议问题