2012-06-18 106 views
2

我有一个JSON问题。JSON解析不与JSONObject一起使用

以下代码是发生错误的位置。我已经验证了结果字符串如下。

{"name":"test", "num1":1.0, "num2":2.0} 

这是代码。

byte[] raw = new byte[1536]; 

try{ 

    DatagramPacket packet = new DatagramPacket(raw, raw.length); 
    mSocket.receive(packet); //Multicast Socket declared in another part of the program 
    String result = new String(packet.getData(), 0, packet.getLength()); 
    JSONObject jObj = new JSONObject(result); 
    String name = jObj.getString("name"); 
} 
catch (JSONException e){ 

} 
catch(Exception eX){ 

} 

但是,我得到一个JSONException,出现以下错误。

没有名称的值。

我的JSON语法有什么问题吗?

感谢,

This is what the string shows me

This is what the json object shows me

+1

不,看起来不错。您可以通过将浏览器指向网址来验证是否真的是你所得到的。 –

+0

你确定你的结果包含{“name”:“test”,“num1”:1.0,“num2”:2.0} ?? – Akram

+0

尝试使用日志从服务中获取确切的字符串并在此处发布。 – DanO

回答

1

它看起来像有与编码的问题。你有没有试过指定UTF-8

String response = new String(packet.getData(), 0, packet.getLength(), "UTF-8"); 

我不确定这个问题可能是什么。剩下的代码看起来是正确的。

+0

在logcat中,我看到以下内容。 06-18 11:50:52.550:I /结果字符串信息(21713):{??“?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ??? ?S 10吨?? “??,??” ?? N 10ù-7 M【1】 “??:【1】ϵ 0 ??,??” 值Σσn ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ??我认为你是正确的编码。但是,我使用了“UTF-8”参数,并且仍然使用相同的字符串。 – DoubleDunk

+0

是的,这是服务器端的编码错误。非常感谢你。 – DoubleDunk

0
String result = "{\"name\":\"test\", \"num1\":1.0, \"num2\":2.0}"; 
JSONObject data = new JSONObject(result); 
System.out.println(data.getString("name")); 
System.out.println(data.get("num1")); 
System.out.println(data.get("num2"));