我正在使用 Gson 提取一些字段。顺便说一下,我不想创建一个类,因为我在所有 JSON 响应中只需要一个值。这是我的回复:
{
"result": {
"name1": "value1",
"name2": "value2",
},
"wantedName": "wantedValue"
}
我需要
wantedValue
,但我不想为反序列化创建整个类。是否可以使用 Gson 实现此目的?
如果您只需要一个字段,请使用
JSONObject
。
import org.json.JSONException;
import org.json.JSONObject;
public class Main {
public static void main(String[] args) throws JSONException {
String str = "{" +
" \"result\": {" +
" \"name1\": \"value1\"," +
" \"name2\": \"value2\"," +
" }," +
" \"wantedName\": \"wantedValue\"" +
"}";
JSONObject jsonObject = new JSONObject(str);
System.out.println(jsonObject.getString("wantedName"));
}
输出:
wantedValue
如果你不必使用 Gson,我会使用 https://github.com/douglascrockford/JSON-java。您可以轻松提取单个字段。我找不到使用 Gson 做这么简单的事情的方法。
你会做
String wantedName = new JSONObject(jsonString).getString("wantedName");
可以只使用gson的一部分,用它来解析json:
Reader reader = /* create reader from source */
Streams.parse(new JsonReader(reader)).getAsJsonObject().get("wantedValue").getAsString();
这是一个适用于 gson 2.10 版本的版本
import com.google.gson.Gson;
import com.google.gson.JsonObject;
public class Main {
public static void main(String[] args) {
String str = "{" +
" \"result\": {" +
" \"name1\": \"value1\"," +
" \"name2\": \"value2\"" +
" }," +
" \"wantedName\": \"wantedValue\"" +
"}";
Gson gson = new Gson();
JsonObject jsonObject = gson.fromJson(str, JsonObject.class);
System.out.println(jsonObject.get("wantedName").getAsString());
}
}