首先,我通常会知道如何反序列化JSON对象。我遇到的特定问题是,我有一个Json对象,其中包含名为"1", "2", "3"
的数组,等等。但是在Java中,我无法声明变量ArrayList<AnotherObject> 1;
,还有比手工替换数字更好的方法吗? ?
Json(大大减少了):
{
"object": {
"1": [{...}],
"2": [{...}],
"3": [{...}],
"4": [{...}],
"5": [{...}],
"6": [{...}],
"7": [{...}]
}
}
预先感谢
答案 0 :(得分:1)
这是使用GSON
来反序列化JSON的方式:
public static void main(String[] args) {
final String json = "{\n" +
" \"object\": {\n" +
" \"1\": [{ \"id\" : 111 }],\n" +
" \"2\": [{ \"id\" : 222 }],\n" +
" \"3\": [{ \"id\" : 333 }]\n" +
" }\n" +
"}\n";
final Gson gson = new GsonBuilder()
.create();
final ObjectWrapper value = gson.fromJson(json, ObjectWrapper.class);
System.out.println(value.object);
System.out.println(value.object.keySet());
System.out.println(value.object.get(1));
}
// This is top-most object we want to deserialize from JSON
static class ObjectWrapper {
// Didn't bother about proper naming while it is better to give a meaningful name here
private Map<Integer, List<Element>> object;
}
static class Element {
// Added this attribute to demonstrate that objects within array are properly read
private int id;
@Override
public String toString() {
return "{id=" + id + "}";
}
}
答案 1 :(得分:0)
这些数字看起来很像数组的索引。如果是这样,您可以删除所有这些对象,并将整个对象设置为数组。这样您将获得一个数组数组。
答案 2 :(得分:0)
我现在正在使用以下解决方法:
json.replace("\"1\"","\"one\"")
.replace("\"2\"","\"two\"")
.replace("\"3\"","\"three\"")
.replace("\"4\"","\"four\"")
.replace("\"5\"","\"five\"")
.replace("\"6\"","\"six\"")
.replace("\"7\"","\"seven\"");
编辑:此解决方案确实有效,但是非常难看。 @yegodm的解决方案效果更好!谢谢你!
答案 3 :(得分:-1)
解决此问题的方法是使代码通过以下方式转换JSON字符串:
{
"object": {
"a1": [{...}],
"a2": [{...}],
"a3": [{...}],
"a4": [{...}],
"a5": [{...}],
"a6": [{...}],
"a7": [{...}]
}
}