【问题标题】:Why does JSONObject.optString add garbage to my strings?为什么 JSONObject.optString 会向我的字符串添加垃圾?
【发布时间】:2011-08-12 18:33:04
【问题描述】:

我从 json 开始:

{
    "Key1" : "Value1",
    "Key2" : "Value2"
}

然后我将这个 json 硬编码到一个字符串中:

String json = "{ \"Key1\" : \"Value1\", \"Key2\" : \"Value2\" }";

接下来我尝试解析 json:

JSONObject content = null;
try {
    content = new JSONObject(json);
} catch (JSONException e) {
    e.printStackTrace();
    return null;
}       

String key1 = content.optString("Key1", null);

如果我查看通过调用 JSONObject 创建的 hashmap,它看起来是正确的:

{Key2=Value2, Key1=Value1}

但是当我在调试器中查看字符串 key1 的值时,我得到了这个:

[V, a, l, u, e, 1, U, U, U, U, U, U, U, U, U, U]

其中 U 似乎是 unicode 字符 25A1(白色方块)。

我也尝试过通用 get("Key1") 方法,将结果转换为字符串,我得到相同的行为?!?

【问题讨论】:

  • 以下返回什么? "Value1".equals(key1);
  • 也许我离这里很远,但是定义一个像这样的 JSON 对象对于所有转义字符来说似乎很痛苦。您是否尝试过使用 myJsonObject.put(string key, object value) 来查看存储的内容?
  • @Jack 这很痛苦,但这只是一个简单的故障排除方法。
  • 啊,明白了 - 是的,我注意到有时在调试时会在我的字符串中附加一堆垃圾。

标签: android json


【解决方案1】:

我没有看到您的代码有问题,因为这个轻微的修改似乎有效:

public static void main(String[] args)
{
    String json = "{ \"Key1\" : \"Value1\", \"Key2\" : \"Value2\" }";

    JSONObject content = null;
    try
    {
        content = new JSONObject(json);
    }
    catch (JSONException e)
    {
        e.printStackTrace();
        return;
    }

    String key1 = content.optString("Key1", null);
    System.out.print(key1 + "end!");
}

控制台输出显示:Value1end!

在调试器中查看代码时,我看到了:

如果我冒险猜测,它可能只是调试器用来保存String 的额外缓冲区空间。您是否尝试过查看您的代码认为它是什么?

"Value1".equals(key1); //should return true if everything is working correctly.

【讨论】:

  • 我的评价也是如此。也许是在调试垃圾,我担心一旦我解析了一个更复杂的对象,我的数组和子对象就会被污染。我可能太偏执了。
  • 有时最好只是编写代码看看会发生什么:)
【解决方案2】:

optString(java.lang.String key) 获取与键关联的可选字符串。

你应该使用

getString(java.lang.String key) 获取与某个键关联的字符串。

还是我错过了什么?

更多:http://www.json.org/javadoc/org/json/JSONObject.html

【讨论】:

    猜你喜欢
    • 2010-12-07
    • 2013-12-18
    • 2012-03-28
    • 1970-01-01
    • 2020-04-19
    • 1970-01-01
    • 2020-03-06
    • 2023-03-31
    • 2016-12-19
    相关资源
    最近更新 更多