我有这个代码,我试图从这个JSON字符串中获取项目,但它失败了。
我正在从远程主机解析Json字符串。
package selectDB;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.sql.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import org.json.simple.*;
public class selectDB
{
public static void main(String[] args) throws IOException, ParseException
{
String s = "";
URL u = new URL("http://192.168.3.1/android/select.php");
URLConnection c = u.openConnection();
InputStream r = c.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(r));
for(String line; (line = reader.readLine()) != null;)
{
s+=line;
}
System.out.println(s);
}
}
结果是
{"result" : "true" , "messages" : [{"id":"866343023633578","latitute":"27","longitude":"31","number_phone":"01113171374"},{"id":"352168066354050","latitute":"27","longitude":"31","number_phone":"202222"},{"id":"50","latitute":"50","longitude":"100","number_phone":"50"},{"id":"110","latitute":"50","longitude":"50","number_phone":"110"},{"id":"120","latitute":"27","longitude":"31","number_phone":"120"},{"id":"130","latitute":"28","longitude":"29","number_phone":"120"},{"id":"140","latitute":"30","longitude":"40","number_phone":"140"},{"id":"800","latitute":"60","longitude":"30","number_phone":"800"},{"id":"353629054230064","latitute":"70","longitude":"80","number_phone":"120"}]}
请帮忙!
答案 0 :(得分:1)
你可以使用JsonReader类。
try (JsonReader in = Json.createReader(r)) {
JsonObject jsonObject= in.readObject();
YourObject obj = new YourObject();
obj.setSomething(jsonObject.getString("something", null));
// "something" is the key in the json file, null is the default
// when "something" was not found
} catch (JsonException | ClassCastException ex) {
throw new BadRequestException("Invalid Json Input");
}
答案 1 :(得分:0)
您也可以使用Google图书馆GSON,它易于使用和自我解释。
https://code.google.com/p/google-gson/
Gson Goals
提供简单的toJson()和fromJson()方法,将Java对象转换为JSON,反之亦然 允许将预先存在的不可修改对象转换为JSON和从JSON转换 广泛支持Java Generics 允许对象的自定义表示 支持任意复杂的对象(具有深层继承层次结构和广泛使用泛型类型)