我使用Gson来extraxt一些字段。顺便说一句,我不想创建一个类,因为我只需要在所有JSON响应中使用一个值。这里是我的回应:如何反序列化JSON中的某些字段?
{
"result": {
"name1": "value1",
"name2": "value2",
},
"wantedName": "wantedValue"
}
我需要wantedValue
但我不希望为反序列化整个类。使用Gson可以实现这个吗?
我使用Gson来extraxt一些字段。顺便说一句,我不想创建一个类,因为我只需要在所有JSON响应中使用一个值。这里是我的回应:如何反序列化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? – Angelo
可以使用GSON的只是一部分,用它只是为了解析JSON:
Reader reader = /* create reader from source */
Streams.parse(new JsonReader(reader)).getAsJsonObject().get("wantedValue").getAsString();
如果你没有使用GSON,我将使用https://github.com/douglascrockford/JSON-java。您可以轻松提取单个字段。我找不到使用Gson这么简单的方法。
你会只是做
String wantedName = new JSONObject(jsonString).getString("wantedName");
你也许可以解析JSON自己找到了“wantedName”值。 – Cruncher
@Cruncher我正在考虑正则表达式,但我希望尽可能避免使用它。 – Angelo
你可以创建一个'ExclusionStrategy',在这里看到:http://stackoverflow.com/questions/4802887/gson-how-to-exclude-specific-fields-from-serialization-without-annotations – Amar