Convert JSON to Map

后端 未结 17 2894
天涯浪人
天涯浪人 2020-11-22 10:20

What is the best way to convert a JSON code as this:

{ 
    \"data\" : 
    { 
        \"field1\" : \"value1\", 
        \"field2\" : \"value2\"
    }
}
         


        
17条回答
  •  失恋的感觉
    2020-11-22 11:06

    My post could be helpful for others, so imagine you have a map with a specific object in values, something like that:

    {  
       "shopping_list":{  
          "996386":{  
             "id":996386,
             "label":"My 1st shopping list",
             "current":true,
             "nb_reference":6
          },
          "888540":{  
             "id":888540,
             "label":"My 2nd shopping list",
             "current":false,
             "nb_reference":2
          }
       }
    }
    

    To parse this JSON file with GSON library, it's easy : if your project is mavenized

    
        com.google.code.gson
        gson
        2.3.1
    
    

    Then use this snippet :

    import com.google.gson.Gson;
    import com.google.gson.JsonElement;
    import com.google.gson.JsonObject;
    import com.google.gson.JsonParser;
    
    //Read the JSON file
    JsonElement root = new JsonParser().parse(new FileReader("/path/to/the/json/file/in/your/file/system.json"));
    
    //Get the content of the first map
    JsonObject object = root.getAsJsonObject().get("shopping_list").getAsJsonObject();
    
    //Iterate over this map
    Gson gson = new Gson();
    for (Entry entry : object.entrySet()) {
        ShoppingList shoppingList = gson.fromJson(entry.getValue(), ShoppingList.class);
        System.out.println(shoppingList.getLabel());
    }
    

    The corresponding POJO should be something like that :

    public class ShoppingList {
    
        int id;
    
        String label;
    
        boolean current;
    
        int nb_reference;
    
        //Setters & Getters !!!!!
    }
    

    Hope it helps !

提交回复
热议问题