2011-08-12 59 views
0

我开始使用JSON:为什么JSONObject.optString将垃圾添加到我的字符串?

{ 
    "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创建的散列表,它看起来是正确的:

{Key2=Value2, Key1=Value1} 

但是,当我看到在调试器中的字符串键1的值,我得到这个:

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

其中U似乎是Unicode字符25A1(白方)。我也试过了泛型get(“Key1”)方法,将结果转换为字符串,我得到相同的行为?!???????????

+0

以下是什么回报? '“Value1”.equals(key1);' –

+0

也许我在这里走了,但定义一个像这样的JSON对象似乎对所有转义字符都很痛苦。你有没有尝试过使用myJsonObject.put(string key,object value)来查看存储的内容? – Jack

+0

@Jack这很痛苦,但它只是一个简单的黑客疑难解答。 –

回答

3

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

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!

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

enter image description here

如果我想冒险猜测,它可能只是调试器用来保存String的附加缓冲区空间。你有没有试过看看你的代码认为它是什么?

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

我的评价也是如此。也许是在调试垃圾,我担心的是,一旦我解析了一个更复杂的对象,那么我的数组和子对象就会被污染。我可能太偏执了。 –

+0

有时最好只编写它,看看会发生什么:) –

相关问题