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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42507328/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 06:41:51  来源:igfitidea点击:

How to convert String to jsonObject in Java?

java

提问by Java

This is string from jsonObject

这是来自 jsonObject 的字符串

{"no":1000,"name":"xxx","code":345}

I want convert to this string to JSONObject. Code here

我想将此字符串转换为 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();
}

回答by Prabhav

Step 1: Add these two lines

第一步:添加这两行

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>

回答by Hyman Flamp

I have used Hymanson. Example here: https://www.mkyong.com/java/Hymanson-2-convert-java-object-to-from-json/

我用过Hyman逊。这里的例子:https: //www.mkyong.com/java/Hymanson-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 nameI will call it User.

创建一个 POJO。我不知道类型是什么,但由于它有名称作为字段,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);