我有以下JSON:
[
{"hex":"3443d3", "squawk":"4673", "flight":"VLG3014 ","lat":37.716344, "lon":-2.913646, "validposition":1, "altitude":35000,"vert_rate":0,"track":225, "validtrack":1,"speed":427, "messages":74, "seen":0},
{"hex":"345313", "squawk":"3767", "flight":"VLG2422 ", "lat":37.573568, "lon":-2.912750, "validposition":1, "altitude":38000, "vert_rate":0,"track":72, "validtrack":1,"speed":420, "messages":1217, "seen":0}
]
代码如下:
@Override
protected String doInBackground(String... strings) {
try {
socket=new Socket("172.24.1.1",9000);
System.out.println("CONECTED");
} catch (IOException e) {
e.printStackTrace();
}
try {
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println("BufferedReader READY");
} catch (IOException e) {
e.printStackTrace();
}
int i=0;
while(i==0) {
try {
System.out.println("WAITING FOR MESSAGE");
inputString=br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(inputString!=null) {
jsonString = new JSONObject(inputString);
System.out.println(parseJSON(jsonString)[0]);
}
} catch (JSONException e) {
//e.printStackTrace();
}
}
return null;
}
private String[] parseJSON(JSONObject jsonObject) throws JSONException {
String hex = jsonObject.getString("hex");
String squawk = jsonObject.getString("squawk");
String flight = jsonObject.getString("flight");
String lat = jsonObject.getString("lat");
String lon = jsonObject.getString("lon");
String validposition = jsonObject.getString("validposition");
String altitude = jsonObject.getString("altitude");
String vert_rate = jsonObject.getString("vert_rate");
String track= jsonObject.getString("track");
String validtrack = jsonObject.getString("validtrack");
String speed = jsonObject.getString("speed");
String messages = jsonObject.getString("messages");
String seen = jsonObject.getString("seen");
String[] answer={hex,squawk,flight,lat,lon,validposition,altitude,vert_rate,track,validtrack,speed,messages,seen};
return answer;
}
我在我的应用中收到了整个JSON。当我得到“hex”时,我获得345313代码。我想要一个带有两个值的“hex”向量,我的问题是: 如何在不使用for循环的情况下获取这两个值?是否有任何JSON方法同时获取它们并将它们保存在数组中?
答案 0 :(得分:1)
根据您的问题,您有一个JSONArray,而不是JSONObject
如果不需要循环,可以使用getJSONObject(0)
和getJSONObject(1)
索引数组来获取两个JsonObject元素。显然循环更好。
然后只需使用getString("hex")
作为两个对象就像你已经做的那样为两者提供相同的密钥。