获取JSONArray的密钥字符串

时间:2017-12-09 14:53:53

标签: java android arrays json

我正在创建一个动态的应用程序,以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
        }

2 个答案:

答案 0 :(得分:0)

而不是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();

答案 1 :(得分:0)

已使用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)));
}