如何在Java中将String转换为jsonObject?

时间:2017-02-28 11:18:02

标签: java

这是来自jsonObject

的字符串
{"no":1000,"name":"xxx","code":345}

我想将此字符串转换为JSONObject。 代码在这里

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();
}

2 个答案:

答案 0 :(得分:3)

第1步:添加这两行

JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(output);

步骤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>

答案 1 :(得分:0)

我用过杰克逊。示例:https://www.mkyong.com/java/jackson-2-convert-java-object-to-from-json/

创建POJO。我不知道类型是什么,但由于它的名称为字段name,我将其称为User

public class User {
    private int no;
    private String name;
    private int code;

    //getters setters
}

然后是这样的:

 User user = mapper.readValue(output, User.class);