简体   繁体   中英

JSON parsing not working with JSONObject

I have a JSON question.

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.

No value for name.

Is there something wrong with my JSON syntax?

Thanks,

这是字符串显示给我的

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

It looks like there is an issue with the encoding. Have you tried specifying 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"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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