Json string parsing to java object with multiple objects

前端 未结 1 1283
盖世英雄少女心
盖世英雄少女心 2021-01-20 11:14

Trying to parse the following json string to java object using gson

{
    \"entry\": \"132456\",
    \"product\": {
        \"item\": \"123456\",
        \"p         


        
相关标签:
1条回答
  • 2021-01-20 12:11

    Try this JSON:

    {
        "entry": "132456",
        "product": 
        {
            "item": "123456",
            "prompts": 
            [
                {
                    "promptId": "1",
                    "promptNumber": "109",
                    "promptType": 4,
                    "promptTypeDesc": "desc1",
                    "validations":
                    [
                        {
                            "minLen": 10,
                            "maxLen": 10,
                            "required": true 
                        } 
                    ] 
                } 
            ] 
        }
    }
    

    With this Java Class:

    import java.util.List;
    
    public class Info {
    
        private String entry;
        private Product product;
    
        public class Product {
    
            private String item;
            private List<Prompt> prompts;
    
            public class Prompt {
    
                private String promptId;
                private String promptNumber;
                private int promptType;
                private String promptTypeDes;
                private List<Validation> validations;
    
                public class Validation {
    
                    private int maxLen;
                    private int minLen;
                    private boolean required;
                }
            }
        }
    }
    

    Works like a charm

    public static void main(String args[]){
    
        String input = "{"
                + "\"entry\": \"132456\","
                + "\"product\": {\"item\": \"123456\","
                + "\"prompts\":[{\"promptId\": \"1\","
                + "\"promptNumber\": \"109\","
                + "\"promptType\": 4,"
                + "\"promptTypeDesc\": \"desc1\","
                + "\"validations\":[{\"minLen\": 10,"
                + "\"maxLen\": 10"
                + ",\"required\": true}]}]}}";
    
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        Info item = gson.fromJson(input, Info.class);
    
        String jsonOutput = gson.toJson(item);
        System.out.println(jsonOutput);
    }
    

    Output:

    run:
    {
      "entry": "132456",
      "product": {
        "item": "123456",
        "prompts": [
          {
            "promptId": "1",
            "promptNumber": "109",
            "promptType": 4,
            "validations": [
              {
                "maxLen": 10,
                "minLen": 10,
                "required": true
              }
            ]
          }
        ]
      }
    }
    BUILD SUCCESSFUL (total time: 0 seconds)
    
    0 讨论(0)
提交回复
热议问题