This is string from jsonObject
{"no":1000,"name":"xxx","code":345}
I want convert to this string to 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
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(output);
Step 2: Add below dependency to 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/
Create a POJO. I don't know what the type is but since it has name as field name
I will call it 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);
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.