Java 使用google gson在hashmap中的json数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21014407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
json array in hashmap using google gson
提问by Jitendra Prajapati
I am new with Gson and I am trying to parse array of object in a Hashmap
, but I am getting com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 3
.
我是 Gson 的新手,我试图解析 a 中的对象数组Hashmap
,但我得到了com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 3
.
My code is
我的代码是
Map<String, String> listOfCountry = new HashMap<String, String>();
Gson gson = new Gson();
Type listType = new TypeToken<HashMap<String, String>>() {}.getType();
listOfCountry = gson.fromJson(sb.toString(), listType);
and JSON is
和 JSON 是
[
{"countryId":"1","countryName":"India"},
{"countryId":"2","countryName":"United State"}
]
采纳答案by Brian Roach
Your JSON is an array of objects, not anything resembling a HashMap
.
您的 JSON 是一个对象数组,而不是类似于HashMap
.
If you mean you're trying to convert that to a List
of HashMap
s ... then that's what you need to do:
如果您的意思是要尝试将其转换为 a List
of HashMap
s ... 那么这就是您需要做的:
Gson gson = new Gson();
Type listType = new TypeToken<List<HashMap<String, String>>>(){}.getType();
List<HashMap<String, String>> listOfCountry =
gson.fromJson(sb.toString(), listType);
Edit to add from comments below:
编辑以从下面的评论中添加:
If you would like to deserialize to an array of Country
POJOs (which is really the better approach), it's as simple as:
如果您想反序列化为一组Country
POJO(这确实是更好的方法),它很简单:
class Country {
public String countryId;
public String countryName;
}
...
Country[] countryArray = gson.fromJson(myJsonString, Country[].class);
That said, it's really better to use a Collection
:
也就是说,使用 a 确实更好Collection
:
Type listType = new TypeToken<List<Country>>(){}.getType();
List<Country> countryList = gson.fromJson(myJsonString, listType);
回答by dimo414
I assume you're trying to create a mapping of countryId
s to countryName
s, correct? This can be done in Gson, but really isn't what it is designed for. Gson is primarily intended translate JSON into equivalent Java objects (e.g. an array into a List, an object into an Object or a Map, etc.) and not for transforming arbitrary JSON into arbitrary Java.
我假设您正在尝试创建countryId
s 到countryName
s的映射,对吗?这可以在 Gson 中完成,但实际上并不是它的设计目的。Gson 主要用于将 JSON 转换为等效的 Java 对象(例如,将数组转换为 List,将对象转换为 Object 或 Map 等),而不是将任意 JSON 转换为任意 Java。
If it's possible, the best thing for you to do would be to refactor your JSON. Consider the following format:
如果可能,您最好的做法是重构您的 JSON。考虑以下格式:
{
"1": "India",
"2": "United State"
}
It's less verbose, easier to read, and most notably, easy to parse with Gson:
它不那么冗长,更容易阅读,最值得注意的是,使用 Gson 很容易解析:
Type countryMapType = new TypeToken<Map<Integer,String>>(){}.getType();
Map<Integer,String> countryMap = gson.fromJson(sb.toString(), countryMapType);
If you cannot edit your JSON syntax, you'll have to manually parse the JSON data into the structure you're trying to create, which will be somewhat tedious and involved. Best to read up on the Gson User Guideto learn how.
如果您无法编辑 JSON 语法,则必须手动将 JSON 数据解析为您尝试创建的结构,这会有些乏味和复杂。最好阅读Gson 用户指南以了解如何操作。
As an aside, you call your Map<String, String>
object listOfCountry
, which is a confusing name - is it a map or a list? Avoid using names like "list" for objects that aren't lists. In this case I would suggest either countries
or countryMap
.
顺便说一句,你称你的Map<String, String>
object listOfCountry
,这是一个令人困惑的名字 - 它是地图还是列表?避免对不是列表的对象使用“列表”之类的名称。在这种情况下,我会建议要么countries
或countryMap
。
回答by jairobjunior
After reading what @dimo414 and @Brian Roach said, if you still want to get a map out of your json structure, you can achieve by doing this:
阅读@dimo414 和@Brian Roach 所说的内容后,如果您仍然想从 json 结构中获取地图,可以通过执行以下操作来实现:
Type type = new TypeToken<HashMap<String, String>>() {}.getType();
Gson gson = new GsonBuilder().registerTypeAdapter(type, new JsonDeserializer<HashMap<String, String>>() {
@Override
public HashMap<String, String> deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
HashMap<String, String> map = new HashMap<>();
for (JsonElement element : jsonElement.getAsJsonArray()) {
JsonObject jsonObject = element.getAsJsonObject();
signals.put(jsonObject.get("countryId").getAsString(), jsonObject.get("countryName").getAsString());
}
return map;
}
}).create();
HashMap<String, String> countries = gson.fromJson(jsonArray, type);
But at that point you could just parse your json into a JsonArray and loop through it making your map.
但那时你可以将你的 json 解析成一个 JsonArray 并循环遍历它来制作你的地图。