简体   繁体   中英

GSON parsing to object

I will be recieving JSON strings in the following format:

{ "type":"groups", "groups":[ {"group":"NAME"}, ...] }

How would one form an object so that the following would work.

MyClass p = gson.fromJson(jsonString, MyClass.class);

The part I'm stuck it is "{"group":"NAME"}". Would this be fixed by saving objects inside the an array? Example.

public class MyClass {

    private String type;
    private List<MyOtherClass> groups = new ArrayList<MyOtherClass>();

    //getter and setter methods

}

Answer: Nesting objects in each other doh! Thanks you guys! Crystal clear now :D

public class MyOtherClass {
    private String group;

    public String getGroup() {
        return group;
    }

    public void setGroup(String group) {
        this.group = group;
    }

    @Override
    public String toString() {
        return "group: "+group;
    }
}

First you need a POJO for the group:

public class MyOtherClass {

   @Expose
   private String group;

   public String getGroup() {
      return group;
   }

   public void setGroup(String group) {
      this.group = group;
   }

}

Next you need one for your 'MyClass', which would look like this:

public class MyClass {

    @Expose
    private String type;

    @Expose
    private List<MyOtherClass> groups = new ArrayList<MyOtherClass>();

    public String getType() {
       return type;
    }

    public void setType(String type) {
       this.type = type;
    }

    public List<Group> getGroups() {
       return groups;
    }

    public void setGroups(List<Group> groups) {
       this.groups = groups;
    }

} 

Hope this helps.

At first glance, this looks fine, assuming MyOtherClass has a field called group that holds a String. What do you mean by "the part I'm stuck [on]"? Perhaps you could post the stack trace you're seeing, a broader description of what you're trying to do, or best of all a SSCCE ?

When using GSON, I find it easiest to implement the class structure I need, then let GSON generate the JSON data from that. You certainly can go the other way (design class structure based on JSON data), but I think it's more confusing if you don't understand what GSON is trying to do.

Some pseduo-code:

Class MyClass
  String type
  List<MyOtherClass> groups

Class MyOtherClass
  String group

Looking at this we can easily see the JSON that will hold our serialized object will look like so:

{
  type: "...",
  groups: [
    { group: "..." },
    ...
  ]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM