簡體   English   中英

如何在Java中將String轉換為jsonObject?

[英]How to convert String to jsonObject in 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();
}

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

我用過傑克遜。 此處的示例: 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM