Gson, how to deserialize array or empty string

前端 未结 6 2263
长情又很酷
长情又很酷 2020-12-06 20:08

I trying to deserialize this json to array of objects:

[{
    \"name\": \"item 1\",
    \"tags\": [\"tag1\"]
},
{
    \"name\": \"item 2\",
    \"tags\": [\"         


        
6条回答
  •  我在风中等你
    2020-12-06 21:03

    Use GSON's fromJson() method to de serialize your JSON.

    You can better understand this by the example given below:

    import java.util.ArrayList;
    import com.google.gson.Gson;
    import com.google.gson.JsonArray;
    import com.google.gson.JsonElement;
    import com.google.gson.JsonParser;
    
    public class JsonToJava {
    
    /**
     * @param args
     */
    public static void main(String[] args) {
        String json = "[{\"firstName\":\"John\", \"lastName\":\"Doe\", \"id\":[\"10\",\"20\",\"30\"]},"
                + "{\"firstName\":\"Anna\", \"lastName\":\"Smith\", \"id\":[\"40\",\"50\",\"60\"]},"
                + "{\"firstName\":\"Peter\", \"lastName\":\"Jones\", \"id\":[\"70\",\"80\",\"90\"]},"
                + "{\"firstName\":\"Ankur\", \"lastName\":\"Mahajan\", \"id\":[\"100\",\"200\",\"300\"]},"
                + "{\"firstName\":\"Abhishek\", \"lastName\":\"Mahajan\", \"id\":[\"400\",\"500\",\"600\"]}]";
    
        jsonToJava(json);
    }
    
    private static void jsonToJava(String json) {
        Gson gson = new Gson();
        JsonParser parser = new JsonParser();
        JsonArray jArray = parser.parse(json).getAsJsonArray();
    
        ArrayList lcs = new ArrayList();
    
        for (JsonElement obj : jArray) {
            POJO cse = gson.fromJson(obj, POJO.class);
            lcs.add(cse);
        }
        for (POJO pojo : lcs) {
            System.out.println(pojo.getFirstName() + ", " + pojo.getLastName()
                    + ", " + pojo.getId());
        }
    }
    

    }

    POJO class:

    public class POJO {
    
      private String        firstName;
      private String        lastName;
      private String[]  id;
      //Getters and Setters.
    

    I hope this will solve your issue.

提交回复
热议问题