Home > OS >  how to iterate through this json object and format it
how to iterate through this json object and format it

Time:09-30

I have multiple JSON files, but they all look similar to this one (some much longer):

{
  "$id": "http://example.com/myURI.schema.json",
  "$schema": "http://json-schema.org/draft-07/schema#",
  "additionalProperties": false,
  "description": "Sample Procedure schema.",
  "properties": {
    "prop1": {
      "description": "",
      "type": "string"
    },
    "prop2": {
      "description": "",
      "type": "number"
    }
    "prop3": {
      "description": "",
      "type": "string"
    }
  }
}

I want to extract the names (ex. "prop1","prop2") along with their types (ex. "string,"number") and format it to look something like the following:

public static class Whatever {
  @JsonProperty
  public String prop1;

  @JsonProperty
  public Integer prop2;

  @JsonProperty
  public String prop3;

  public Whatever() {}

  public Whatever(String prop1, Integer prop2, String prop3){
    this(prop1, prop2, prop3);
  }
}

I've never used java before so I'm not sure where to begin in creating this script. Mainly I'm concerned with how I will iterate through the json object. Any guidance would be great. Thanks.

CodePudding user response:

I would Approach this this way:

  1. Create a main class that holds all the information of the JSON and a Secondary class that keeps the information of the prop properties of the JSON:
public class MainJsonObject
{
    private int $id;
    private int $schema;
    
    // All the other objects that you find relevant...
    
    private List<SecondaryJsonObject> propsList = new ArrayList<>(); // This will keep all your other props with description and type
    
    // Getter and setter, do not forget them as they are needed by the JSON library!!

}

public class SecondaryJsonObject
{
    private String description;
    private String type;
    
    // Getter and setter, do not forget them !!
}
  1. You could iterate through your JSON Object this way:

First of all include the JSON Library in your project.

Then iterate through your JSON like this:

JSONObject jsonObject = new JSONObject(jsonString);

MainJsonObject mjo = new MainJsonObject();
mjo.set$id(jsonObject.getInt("$id")); // Do this for all other "normal" attributes

// Then we start with your properties array and iterate through it this way:

JSONArray jsonArrayWithProps = jsonObject.getJSONArray("properties");

for(int i = 0 ; i < jsonArrayWithProps.length(); i  )
{
    JSONObject propJsonObject = jsonArrayWithProps.getJSONObject(i); // We get the prop object 

    SecondaryJsonObject sjo = new SecondaryJsonObject();
    sjo.setDescription(propJsonObject.getString("description"));
    sjo.setTyoe(propJsonObject.getString("type"));
    
    mjo.getPropsList().add(sjo); // We fill our main object's list.

}

Good luck!

  • Related