问题
I have the following string:
"[{\"type\":\"string\",\"value\":\"value1\",\"field\":\"label\"},
{\"type\":\"string\",\"value\":\"value2\",\"field\":\"address_unique\"}]"
and I want to turn this into java GSON JsonObject array/list in order to invoke something like:
myJsonObjs[i].getAsJsonPrimitive("value").getAsString();
What is the shortest path to achieve this? I tried setting up a bean like this:
public static class Filter {
@SerializedName("type")
private String type;
@SerializedName("value")
private String value;
@SerializedName("field")
private String field;
//getters, setters and ctor
}
but I cannot find a way to deserialize the string above into an array/list of this bean using JsonParser or Gson. In particular I tried
Gson gson = new Gson();
gson.fromJson(json_string, Filter[].class);
(where json_string is the string above) but this gives me a
IllegalStateException: Expected BEGIN_ARRAY but was STRING
Thank you for your help!
回答1:
Here is one way of doing it:
final String json = "[{\"type\":\"string\",\"value\":\"value1\",\"field\":\"label\"},{\"type\":\"string\",\"value\":\"value2\",\"field\":\"address_unique\"}]";
final JsonParser parser = new JsonParser();
final JsonElement rootElement = parser.parse(json);
final JsonArray values = rootElement.getAsJsonArray();
for (final JsonElement value : values) {
final JsonObject obj = value.getAsJsonObject();
final Filter filter = new Filter();
filter.setType(obj.get("type"));
filter.setValue(obj.get("value"));
filter.setField(obj.get("field"));
}
And here is a more automated way:
final String json = "[{\"type\":\"string\",\"value\":\"value1\",\"field\":\"label\"},{\"type\":\"string\",\"value\":\"value2\",\"field\":\"address_unique\"}]";
final TypeToken<List<Filter>> token = new TypeToken<List<Filter>>() {
};
final Gson gson = new Gson();
final List<Filter> values = gson.fromJson(json, token.getType());
回答2:
What have you tried with parse? What you have there is a string, you need two steps
- parse the string into a JsonArray
- Convert the JsonArray to the java object with fromJson
回答3:
This looks strange, your code should work... Anyway you could also try Genson library, it has similar features to Gson plus some others and better performances.
Here is how to achieve it with Genson:
Genson genson = new Genson();
Filter[] filters = genson.deserialize(json, Filter[].class);
// or if you need a list
List<Filter> filters = genson.deserialize(json, new GenericType<List<Filter>>(){});
回答4:
it can be first parsed into an array, then converted to a list.
final Gson gson = new Gson();
final Filter[] values = gson.fromJson(json, Filter[].class);
ArrayList< Filter > filterList = new ArrayList< Filter >(Arrays.asList(values));
来源:https://stackoverflow.com/questions/14205743/unnamed-json-array-into-java