gpt4 book ai didi

java - 如何在 Java 中发布 JSON 字符串

转载 作者:行者123 更新时间:2023-12-01 15:39:04 26 4
gpt4 key购买 nike

我正在尝试发布一个包含推文的大型 JSON 字符串。其中一些推文包含双引号和许多特殊字符。我需要对 JSON 字符串进行编码吗?如果推文中没有特殊字符或双引号,我的代码就可以工作,否则我不会得到响应。

String jsonString = "{'data': [";

for (Tweet tweet : tweets) {
jsonString +="{'text': '" + tweet.getText() + "'},";
}
jsonString += "]}";

public void analyseTweets(String jsonString){
try {
// Send data
URL url = new URL("http://twittersentiment.appspot.com/api/bulkClassifyJson");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(jsonString);
wr.flush();

// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
wr.close();
rd.close();
} catch (Exception e) {
System.out.print("Error dude!: " + e);
}
}

最佳答案

为什么不使用外部库,例如 google-gson为您处理 JSON 编码?

来自项目描述:

Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.

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

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