如何遍历此 json 对象并对其进行格式化

how to iterate through this json object and format it

我有多个 JSON 个文件,但它们看起来都与这个相似(有些更长):

{
  "$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"
    }
  }
}

我想提取名称(例如“prop1”、“prop2”)及其类型(例如“string”、“number”)并将其格式化为如下所示:

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);
  }
}

我以前从未使用过 java,所以我不确定从哪里开始创建这个脚本。我主要关心如何遍历 json 对象。任何指导都会很棒。谢谢

我会这样处理:

  1. 创建一个包含 JSON 的所有信息的主 class 和一个保留 [=31] 的 prop 属性信息的辅助 class =]:
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. 您可以这样遍历 JSON 对象:

首先在您的项目中包含 JSON 库。

然后像这样遍历 JSON:

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.

}