简体   繁体   English

JSON解析不适用于JSONObject

[英]JSON parsing not working with JSONObject

I have a JSON question. 我有一个JSON问题。

The following code is where the error occurs. 以下代码是发生错误的地方。 I have verified the result string is the following. 我已经验证了结果字符串如下。

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

and this is the code. 这是代码。

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){

}

However I get a JSONException with the following error. 但是,我得到一个JSONException与以下错误。

No value for name. 名称没有值。

Is there something wrong with my JSON syntax? 我的JSON语法有问题吗?

Thanks, 谢谢,

这是字符串显示给我的

这就是json对象向我展示的内容

It looks like there is an issue with the encoding. 看起来编码有问题。 Have you tried specifying UTF-8 您是否尝试过指定UTF-8

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

I'm not sure what the issue could be. 我不确定是什么问题。 The rest of your code looks correct. 您的其余代码看起来正确。

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"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM