【问题标题】:Get JSONArray's Key String获取 JSONArray 的密钥字符串
【发布时间】:2017-12-09 14:53:52
【问题描述】:

我正在制作一个动态到 json 模板的应用程序(应用程序从互联网读取模板),我需要读取 JSONArray 的密钥字符串。

我的 json:

{
  "format": {
    "Drive": [
      "Mecanum",
      "Omni",
      "Regular"
    ],
    "Drive-Configuration": [
      "H",
      "X"
    ],
    "Glyph-Elevator": [
      "Parallel Elevator",
      "Stick Elevator",
      "Strip Elevator"
    ],
    "Glyph-Picker": [
      "Strip Picker",
      "Dual-Servo Picker"
    ],
    "Relic-Elevator": [
      "Horizontal Parallel"
    ],
    "Relic-Holder": [
      "Pliers",
      "Dual-Servo With Rubber Pads"
    ],
    "CypherBox-Fill": [
      "0",
      "1",
      "2",
      "3",
      "4",
      "5",
      "6",
      "7",
      "8",
      "9",
      "10",
      "11",
      "12"
    ],
    "Autonomous": [
      "Poor",
      "Minimal",
      "Okay",
      "Good",
      "Almost Perfect",
      "Perfect"
    ]
  }
}

我想要的是通过代码读取“驱动器”和“驱动器配置”名称。

我有什么:

JSONObject reader=new JSONObject(template);
        JSONArray config=reader.getJSONArray("format");
        for(int type=0;type<config.length();type++){
            JSONArray con=config.getJSONArray(type);
            //Here I Want To Read The Array's Name
        }

【问题讨论】:

标签: java android arrays json


【解决方案1】:

而不是JSON Parser 使用GSON.!

将此添加到您的gradle

compile 'com.google.code.gson:gson:2.8.1'

创建一个ClassMain.!

class MainClass{

@SerializedName("format") 
Value format;



}

Class value{

@SerializedName("Drive") 
ArrayList<String> drive;


@SerializedName("Drive-Configuration") 
ArrayList<String> driveConfiguration;


generate getter and setter.!


}




   and then Convert your JSON to GSON.! 

    MainClass mainClass= new Gson().fromJson(json.toString(), MainClass.class);


    mainClass.getFormat().getDirve();

【讨论】:

    【解决方案2】:

    使用JSONObject.names(); 读名字

    ArrayList<Template> tm = new ArrayList<>();
    JSONObject reader = new JSONObject(format);
    JSONObject config = reader.getJSONObject("format");
    Iterator<String> types = config.keys();
    while (types.hasNext()) {
    String name = types.next();
    tm.add(new Template(name, config.getJSONArray(name)));
    }
    

    【讨论】:

      猜你喜欢
      • 2021-09-01
      • 1970-01-01
      • 2021-02-08
      • 2016-06-30
      • 1970-01-01
      • 2020-11-20
      • 1970-01-01
      • 2022-11-17
      • 2020-09-08
      相关资源
      最近更新 更多