有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何迭代这个json对象并格式化它

我有多个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) 个答案

  1. # 1 楼答案

    我会这样做:

    1. 创建一个包含JSON所有信息的主类和一个保存JSON的prop属性信息的次类:
    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:

    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.
    
    }