gpt4 book ai didi

java - 将简单的 JSON 字符串转换为对象

转载 作者:行者123 更新时间:2023-11-29 20:19:59 25 4
gpt4 key购买 nike

我有这门课:

public class MyClass {
public int number;
public long date;
}

我有一个 JSON 字符串,我正在通过以下操作将其转换为 MyClass 对象:

String s = "{\"Number\":2,\"Date\":1444953600}";
MyClass temp = new Gson().fromJson(s, MyClass.class);

但是,我遇到了以下异常:

Caused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 2 path $

at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:387)

at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:210)

我做错了什么?

编辑

根据要求,这是完整的代码:

URL url = new URL(some_url);
HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
connection.setRequestMethod("GET");

BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuffer response = new StringBuffer();

String inputLine;
while ((inputLine = reader.readLine()) != null) {
response.append(inputLine);
}
reader.close();

MyClass temp = new Gson().fromJson(response.toString(), MyClass.class);

更新类是:

public class MyClass implements Serializable {
@SerializedName("Number")
public int number;

@SerializedName("Date")
public long date;
}

最佳答案

使用注解@SerializedName,如:

public class MyClass {
@SerializedName("Number")
public int number;
@SerializedName("Date")
public long date;
}

关于java - 将简单的 JSON 字符串转换为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33343981/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com