我使用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