【问题标题】:String value as Object key字符串值作为对象键
【发布时间】:2013-08-09 12:50:28
【问题描述】:

假设我有 String A = "A";String B = "B";,我想将这些值用作 json 对象中的键。

{
    "A":"string1",
    "B":"string2"
}

现在在另一个时空,我想从Json Object 中获取这些String 值。我必须得到“A”和“B”的值。我们可以在制作这个 json 对象时只使用 A 和 B 并在获取值时重用它们。

但是,我正在尝试从实际的 Object 中创建一个 Json Object。我正在使用Gson 来实现这一点。制作对象时如何使用 A 和 B 作为键?

【问题讨论】:

  • 您能告诉我们您当前的代码吗?
  • 您可以使用AB 作为键创建Map<String,String>,并使用GSON 对其进行序列化。要返回 AB,可以将其反序列化为 Map 并获取密钥

标签: java android json gson key-value


【解决方案1】:

使用Gson,您可以将JSON解析为Map as

String json = "{\n" +
        "\"A\":\"string1\",\n" +
        "\"B\":\"string2\"\n" +
    "}";

Gson gson = new Gson();
Type type = new TypeToken<Map<String, String>>(){}.getType();

Map<String, String> map = gson.fromJson(json, type);

System.out.println(map.get("A")); // string1
System.out.println(map.get("B")); // string2

或者,如果您想将密钥包装在已经存在的对象中

String json = "{ pairs : {\n" +
        "\"A\":\"string1\",\n" +
        "\"B\":\"string2\"\n" +
    "} }";

Gson gson = new Gson();

JsonObject jsonObject = gson.fromJson(json, JsonObject.class);

System.out.println(jsonObject.getPairs().get("A")); // string1
System.out.println(jsonObject.getPairs().get("B")); // string2

JsonObject 的样子

class JsonObject {
    private Map<String, String> pairs;

    public Map<String, String> getPairs() {
        return pairs;
    }
}

【讨论】:

    猜你喜欢
    • 2016-04-28
    • 2021-09-06
    • 2020-09-27
    • 2019-09-24
    • 1970-01-01
    • 1970-01-01
    • 2020-06-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多