如何使用getJSONArray方法访问json对象的嵌套元素

Sri*_*iks 47 java arrays json

我有一个JSON响应,如下所示:

{
  "result": {
    "map": {
      "entry": [
        {
          "key": { "@xsi.type": "xs:string", "$": "ContentA" },
          "value": "fsdf"
        },
        {
          "key": { "@xsi.type": "xs:string", "$": "ContentB" },
          "value": "dfdf"
        }
      ]
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我想访问"entry"数组对象的值.我想访问:

RESPONSE_JSON_OBJECT.getJSONArray("entry");
Run Code Online (Sandbox Code Playgroud)

我到了JSONException.有人可以帮我从上面的JSON响应中获取JSON数组吗?

rud*_*ist 74

您必须分解完整对象才能到达entry阵列.

假设REPONSE_JSON_OBJECT已经解析了JSONObject.

REPONSE_JSON_OBJECT.getJSONObject("result")
    .getJSONObject("map")
    .getJSONArray("entry");
Run Code Online (Sandbox Code Playgroud)

  • 是的,你可以这样做,但是如果你想获取一个元素(如果存在),则它非常脆弱,否则返回 null(或表现得文明)。getString("result.map.entry[1].value") 会很好,如果存在则获取该值,否则为 null。检查每个级别的元素是否存在,然后将其转换并获取子元素,这有点痛苦。 (2认同)

Mic*_*ber 10

我建议你使用Gson库.它允许将JSON字符串解析为对象数据模型.请看我的例子:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.SerializedName;

public class GsonProgram {

    public static void main(String... args) {
        String response = "{\"result\":{\"map\":{\"entry\":[{\"key\":{\"@xsi.type\":\"xs:string\",\"$\":\"ContentA\"},\"value\":\"fsdf\"},{\"key\":{\"@xsi.type\":\"xs:string\",\"$\":\"ContentB\"},\"value\":\"dfdf\"}]}}}";

        Gson gson = new GsonBuilder().serializeNulls().create();
        Response res = gson.fromJson(response, Response.class);

        System.out.println("Entries: " + res.getResult().getMap().getEntry());
    }
}

class Response {

    private Result result;

    public Result getResult() {
        return result;
    }

    public void setResult(Result result) {
        this.result = result;
    }

    @Override
    public String toString() {
        return result.toString();
    }
}

class Result {

    private MapNode map;

    public MapNode getMap() {
        return map;
    }

    public void setMap(MapNode map) {
        this.map = map;
    }

    @Override
    public String toString() {
        return map.toString();
    }
}

class MapNode {

    List<Entry> entry = new ArrayList<Entry>();

    public List<Entry> getEntry() {
        return entry;
    }

    public void setEntry(List<Entry> entry) {
        this.entry = entry;
    }

    @Override
    public String toString() {
        return Arrays.toString(entry.toArray());
    }
}

class Entry {

    private Key key;
    private String value;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public Key getKey() {
        return key;
    }

    public void setKey(Key key) {
        this.key = key;
    }

    @Override
    public String toString() {
        return "[key=" + key + ", value=" + value + "]";
    }
}

class Key {

    @SerializedName("$")
    private String value;

    @SerializedName("@xsi.type")
    private String type;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    @Override
    public String toString() {
        return "[value=" + value + ", type=" + type + "]";
    }
}
Run Code Online (Sandbox Code Playgroud)

节目输出:

Entries: [[key=[value=ContentA, type=xs:string], value=fsdf], [key=[value=ContentB, type=xs:string], value=dfdf]]
Run Code Online (Sandbox Code Playgroud)

如果你不熟悉这个库,那么你可以在" Gson用户指南 "中找到很多信息.


Mah*_*iad 6

使用Gson库尝试此代码并完成工作.

Gson gson = new GsonBuilder().create();

JsonObject job = gson.fromJson(JsonString, JsonObject.class);
JsonElement entry=job.getAsJsonObject("results").getAsJsonObject("map").getAsJsonArray("entry");

String str = entry.toString();

System.out.println(str);
Run Code Online (Sandbox Code Playgroud)


eab*_*hev 5

这是给尼古拉的。

    public static JSONObject setProperty(JSONObject js1, String keys, String valueNew) throws JSONException {
    String[] keyMain = keys.split("\\.");
    for (String keym : keyMain) {
        Iterator iterator = js1.keys();
        String key = null;
        while (iterator.hasNext()) {
            key = (String) iterator.next();
            if ((js1.optJSONArray(key) == null) && (js1.optJSONObject(key) == null)) {
                if ((key.equals(keym)) && (js1.get(key).toString().equals(valueMain))) {
                    js1.put(key, valueNew);
                    return js1;
                }
            }
            if (js1.optJSONObject(key) != null) {
                if ((key.equals(keym))) {
                    js1 = js1.getJSONObject(key);
                    break;
                }
            }
            if (js1.optJSONArray(key) != null) {
                JSONArray jArray = js1.getJSONArray(key);
                JSONObject j;
                for (int i = 0; i < jArray.length(); i++) {
                    js1 = jArray.getJSONObject(i);
                    break;
                }
            }
        }
    }
    return js1;
}


public static void main(String[] args) throws IOException, JSONException {
    String text = "{ "key1":{ "key2":{ "key3":{ "key4":[ { "fieldValue":"Empty", "fieldName":"Enter Field Name 1" }, { "fieldValue":"Empty", "fieldName":"Enter Field Name 2" } ] } } } }";
    JSONObject json = new JSONObject(text);
    setProperty(json, "ke1.key2.key3.key4.fieldValue", "nikola");
    System.out.println(json.toString(4));

}
Run Code Online (Sandbox Code Playgroud)

如果对兄弟有帮助,请不要忘记维护我的声誉)))