如何从 JSON 字符串创建 JAVA 对象?

How to create JAVA object from JSON string?

我正在创建一个向 API 发出 GET 请求并接收 JSON 的应用程序,我需要创建 class 来保存信息。这是我试过的:

package apiwebapprequest;

import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;


public class APIWebAppRequest {


public static void main(String[] args) throws IOException {
    Gson gson = new Gson();
    Object obj = new Object();

    try {   
 URL url = new URL("xxx");
 URLConnection yc = url.openConnection();
 BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
 String inputLine;

 while((inputLine = in.readLine())!= null){
     System.out.println(inputLine);

     in.close();
     gson.toJson(obj,inputLine);




 }

 }catch(Exception e) {System.out.println(e);}



}

}

这是对象 class:

package apiwebapprequest;

public class Object {


private String cif;
private String data_creare;

public String getCif() {
    return cif;
}

public void setCif(String cif) {
    this.cif = cif;
}

public String getData_creare() {
    return data_creare;
}

public void setData_creare(String data_creare) {
    this.data_creare = data_creare;
}




}

第 29 行 -> gson.toJson(obj,inputLine);它给了我一个错误。你能告诉我怎么做吗?我找不到如何修复它或以其他有效方式修改它

我的想法是当我在 inputLine 中发出请求时我有 json 并且我想在对象属性中单独保存字段

您应该先在 while 循环中阅读整个响应,然后在 while 循环结束后转换为 json。 您可以修改您的代码,例如

StringBuilder sb = new StringBuilder();
while((inputLine = in.readLine())!= null){
     System.out.println(inputLine);
     sb.append(inputLine +"\n");
     in.close();
 }
gson.toJson(obj,sb.toString());

尝试在 while 循环后使用 gson.toJson(obj,inputLine)

假设 json 是

{
"foo":"bar",
"foo1":"bar1"
}

每一行都不是有效的 JSON。 因此,您需要先读取整个字符串,然后再对其进行解析。

您可以使用 Jackson class com.fasterxml.jackson.databind.ObjectMapper

以下是如何将 json 解析为 class:

ObjectMapper objectMapper = new ObjectMapper();
MyClass myClass = objectMapper.readValue(json, MyClass.class);

您可以使用以下方式

gson.toJson(obj); // is used to convert object to JSON

如果您想将 JSON 转换为 Java 对象,那么您可以使用

gson.fromJson(json, Car.class);

例如

     public class Car {
            public String brand = null;
            public int    doors = 0;
   // add getter and setter

        }

String json = "{\"brand\":\"Jeep\", \"doors\": 3}";

Gson gson = new Gson();

Car car = gson.fromJson(json, Car.class);