gpt4 book ai didi

java - 如何在 Java 中解析 JSON 字符串中的项目

转载 作者:行者123 更新时间:2023-12-01 11:22:51 26 4
gpt4 key购买 nike

我有这段代码,我尝试从这个 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"}]}

请帮忙!

最佳答案

你可以使用 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");
}

关于java - 如何在 Java 中解析 JSON 字符串中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31048704/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com