Home > Software design >  Creating nested json objects in Java
Creating nested json objects in Java

Time:01-24

I need to create JSON like below to send with a POST request. So far I tried to accomplish this by using Org.Json library

"Configs": {
 "TeamEvents": {
    "3050": [1,2,3,4,5,6,7,8],
    "3052": [1,2,8],
    "3054": [4]
 }

4 digit numbers are ids. However I could not grasp how can I do this part. I've created TeamEvents JSONObject and added id's and arrays with JSONObject.put() method but I dont know how can I pass that TeamEvents object to Configs. Thanks in advance

CodePudding user response:

I understand that you need 3 different classes. You can create plain old Java objects from JSON or JSON-Schema using this site.

RequestBody Class

public class RequestBody {

    @SerializedName("Configs")
    @Expose
    private Configs configs;

    public Configs getConfigs() {
       return configs;
    }

    public void setConfigs(Configs configs) {
        this.configs = configs;
    }
}

Configs Class

public class Configs {

    @SerializedName("TeamEvents")
    @Expose
    private TeamEvents teamEvents;

    public TeamEvents getTeamEvents() {
        return teamEvents;
    }

    public void setTeamEvents(TeamEvents teamEvents) {
        this.teamEvents = teamEvents;
    }
}

TeamEvents Class

public class TeamEvents {

    @SerializedName("id")
    @Expose
    private List<Integer> id = null;

    public List<Integer> getId() {
        return id;
    }

    public void setId(List<Integer> id) {
        this.id = id;
    }
}

CodePudding user response:

You've basically already found your solution, you just haven't realised it!

You can add a JSONObject to a JSONObject.

So you can create your teamEvents JSONObject, .put("each id", value) , then create a new configs JsonObject, and configsObject.put("TeamEvents", teamEventsObject).

Or indeed as Enes has implied, you could do it via creation of java POJOs, then serialize those objects into json, eg. with the Jackson objectMapper. This would be a more solid 'contract' than hardcoding string JSONObjects, but both ways achieve the same result.

CodePudding user response:

Use Gson Library.

Check user guide for more complex example.

Simple Example


class DataClass {
    private int code = 1;
    private String name = "abc";
    DataClass() {
        // no-args constructor
    }
}

// Serialization
DataClass data = new DataClass();
Gson gson = new Gson();
String json = gson.toJson(data);

// ==> json is {"code":1,"name":"abc"}
    
// Deserialization
DataClass data = gson.fromJson(json, DataClass.class);
  •  Tags:  
  • Related