[英]How to convert String to jsonObject in Java?
This is string from jsonObject 这是jsonObject的字符串
{"no":1000,"name":"xxx","code":345}
I want convert to this string to JSONObject. 我想将此字符串转换为JSONObject。 Code here
在这里编码
try {
URL url = new URL("http://localhost:8090/search?numer="+no);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output ;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);//output:{"no":1000,"name":"xxx","code":345}
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Step 1: Add these two lines 步骤1:添加这两行
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(output);
Step 2: Add below dependency to pom.xml 步骤2:将以下依赖项添加到pom.xml
<!-- https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple -->
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1</version>
</dependency>
I have used Jackson. 我用过杰克逊。 Example here: https://www.mkyong.com/java/jackson-2-convert-java-object-to-from-json/
此处的示例: https : //www.mkyong.com/java/jackson-2-convert-java-object-to-from-json/
Create a POJO. 创建一个POJO。 I don't know what the type is but since it has name as field
name
I will call it User
. 我不知道类型是什么,但是由于它具有名称作为字段
name
我将其称为User
。
public class User {
private int no;
private String name;
private int code;
//getters setters
}
Then something like this: 然后是这样的:
User user = mapper.readValue(output, User.class);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.