我从gmail标头获得了这种json数据。我怎样才能解析它以获得android中“传递到”和“收到”的值。提前谢谢。
[
{"name":"Delivered-To","value":"ayuka******l@gmail.com"},
{"name":"Received","value":"by 10.140.22.233 with SMTP id 96csp129737qgn; Tue, 12 Sep 2017 14:11:47 -0700 (PDT)"},
{"name":"X-Google-Smtp-Source","value":"ADKCNb5EL+VcU9VEZ4HxoicjzSkTx8DxijwG+0LOR+My5P4fQoiAwNEY8LYBEN/kCq+ITzM43nDg"},
{"name":"X-Received","value":"by 10.129.183.31 with SMTP id v31mr14525436ywh.24.1505250707382; Tue, 12 Sep 2017 14:11:47 -0700 (PDT)"}
]
答案 0 :(得分:3)
您只需要通过索引获取JSON对象,然后获取json字段" name"在这种情况下
JSONArray yourData = new JSONArray(jsonFromGmail); // Put your data inside a JSONArray
String name = "";
try {
for (int i = 0; i < yourData.length(); i++) {//Loop through your JSON array
JSONObject jsonobj = null;
jsonobj = yourData.getJSONObject(i); //Get JSONObjects by index
System.out.println("name : " + i + " = " + jsonobj.getString("name"));
name = jsonobj.getString("name");
// Do whatever you want with the string
}
} catch (JSONException e) {
e.printStackTrace();
}
希望有所帮助
答案 1 :(得分:1)
这可以使用Gson(有关安装说明和文档,请参阅https://github.com/google/gson):
String json = "[ {\"name\":\"Delivered-To\",\"value\":\"ayuka******l@gmail.com\"}, {\"name\":\"Received\",\"value\":\"by 10.140.22.233 with SMTP id 96csp129737qgn; Tue, 12 Sep 2017 14:11:47 -0700 (PDT)\"}, {\"name\":\"X-Google-Smtp-Source\",\"value\":\"ADKCNb5EL+VcU9VEZ4HxoicjzSkTx8DxijwG+0LOR+My5P4fQoiAwNEY8LYBEN/kCq+ITzM43nDg\"}, {\"name\":\"X-Received\",\"value\":\"by 10.129.183.31 with SMTP id v31mr14525436ywh.24.1505250707382; Tue, 12 Sep 2017 14:11:47 -0700 (PDT)\"}]";
// parse the JSON string as an array
JsonArray array = new Gson().fromJson(json, JsonArray.class);
String deliveredTo = "";
String received = "";
// iterate through the items of the array
for (int i = 0; i < array.size(); i++) {
// parse each item as a JSON object, extract name and value from it
JsonObject element = array.get(i).getAsJsonObject();
String name = element.get("name").getAsString();
String value = element.get("value").getAsString();
// look for the relevant fields in name; if we found them, set the according values
if (name.equals("Delivered-To")) {
deliveredTo = value;
} else if (name.equals("Received")) {
received = value;
}
}
System.out.println("Delivered to: " + deliveredTo);
System.out.println("Received: " + received);
在你将它用于制作之前,你当然应该添加一些关于Json有效性的检查,而不是像我在这里做的那样假设(例如:name
和value
存在于每个项目中数组)。
答案 2 :(得分:0)
工作正常。
JSONArray emailHeaderObj = null;
String deliveredTo = " ";
String received = " ";
String Subject = " ";
String from = "";
try {
emailHeaderObj = new JSONArray(emailHeaderString);
for (int i = 0; i < emailHeaderObj.length(); i++) {
JSONObject element = emailHeaderObj.getJSONObject(i);
String name = element.getString("name");
String value = element.getString("value");
switch(name){
case "Date":
received = value;
break;
case "Subject":
Subject = value;
break;
case "From":
from = value;
break;
}
}
} catch (JSONException e) {
e.printStackTrace();
}