Converting JSON to Java object using Gson

前端 未结 2 513
[愿得一人]
[愿得一人] 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" } }
    

提交回复
热议问题