Array of JSON Object to Java POJO

前端 未结 3 2023
情歌与酒
情歌与酒 2020-11-22 09:49

Converting this JSON object as a class in java, how would the mapping be in your POJO Class?

{
    \"ownerName\": \"Robert\",
    \"pets\": [
        {
             


        
相关标签:
3条回答
  • 2020-11-22 10:36

    This kind of question is very popular and needs general answer. In case you need generate POJO model based on JSON or JSON Schema use www.jsonschema2pojo.org. Example print screen shows how to use it:

    How to use it:

    1. Select target language. Java in your case.
    2. Select source. JSON in your case.
    3. Select annotation style. This can be tricky because it depends from library you want to use to serialise/deserialise JSON. In case schema is simple do not use annotations (None option).
    4. Select other optional configuration options like Include getters and setters. You can do that in your IDE as well.
    5. Select Preview button. In case schema is big download ZIP with generated classes.

    For your JSON this tool generates:

    public class Person {
    
     private String ownerName;
     private List <Pet> pets = null;
    
     public String getOwnerName() {
      return ownerName;
     }
    
     public void setOwnerName(String ownerName) {
      this.ownerName = ownerName;
     }
    
     public List < Pet > getPets() {
      return pets;
     }
    
     public void setPets(List < Pet > pets) {
      this.pets = pets;
     }
    
    }
    
    public class Pet {
    
     private String name;
    
     public String getName() {
      return name;
     }
    
     public void setName(String name) {
      this.name = name;
     }
    }
    

    For Android Studio and Kotlin read RIP http://www.jsonschema2pojo.org.

    0 讨论(0)
  • 2020-11-22 10:38

    In the above json you have ownerName as property, pets as List of objects

    public class Response {
    
      private String ownerName;
    
      private List<Pet> pets;
    
      // getters and setters
      }
    

    Pet POJO

    public class Pet {
    
     private String name;
    
     //getters and setters
    
      }
    
    0 讨论(0)
  • 2020-11-22 10:43

    You can use the following classes:

    public class MyObject {
        private String ownerName;
        private List<Pet> pets;
    }
    
    public class Pet {
        private String name;
    }
    
    0 讨论(0)
提交回复
热议问题