本文介绍了让GSON在需要阵列的地方接受单个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我有一堆模型类,它们的字段类型为 code> annotation: $ b Now you just have to tell Gson which fields are not well-formed.Of course, you might configure the whole Gson instance to accept such lists, but let it be more precise using the @JsonAdapter annotation:final class Model { @JsonAdapter(AlwaysListTypeAdapterFactory.class) final List<String> foo = null; @JsonAdapter(AlwaysListTypeAdapterFactory.class) final List<SomeObject> bleh = null; @Override public String toString() { return "Model{" + "foo=" + foo + ", bleh=" + bleh + '}'; }}final class SomeObject { final String some = null; @Override public String toString() { return "SomeObject{" + "some='" + some + '\'' + '}'; }}测试数据:{ "foo": "bar", "bleh": {"some": "object"}} list.json list.json{ "foo": ["bar"], "bleh": [{"some": "object"}]}示例: / p> Example:private static final Gson gson = new Gson();public static void main(final String... args) throws IOException { for ( final String resource : ImmutableList.of("single.json", "list.json") ) { try ( final JsonReader jsonReader = getPackageResourceJsonReader(Q43412261.class, resource) ) { final Model model = gson.fromJson(jsonReader, Model.class); System.out.println(model); } }} p> And the output: 这篇关于让GSON在需要阵列的地方接受单个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-28 20:42