我有下一个json:
{
"blabla": {
"1": {
"foo": "foo1",
"bar": "bar1"
},
"22": {
"foo": "foo22",
"bar": "bar22"
}
}
}
是对象的int映射 有没有办法将其转换为对象数组,如:
class FooBar
{
public int id;
public String foo;
public String bar;
}
没有解析为map并迭代它以进行转换?
答案 0 :(得分:0)
根据您粘贴的StaggeredGridLayoutManager
,我可以假设类结构如下(...是的,您的json无法解析为您的json
类。因为FooBar
表示json
为关键字,但id
类包含FooBar
作为成员变量。因此,它们无法相互转换。):
id
而且,这是示例代码。
class FooBar {
public String foo;
public String bar;
};
class FooBarObject {
public HashMap<String, FooBar> blabla;
public void setBlabla(HashMap<String, FooBar> blabla) {
this.blabla = blabla;
}
public HashMap<String, FooBar> getBlabla() {
return blabla;
}
};
但是,我猜错了......你真的想用import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/**
* Hello world!
*/
class FooBar {
public String foo;
public String bar;
};
class FooBarObject {
public HashMap<String, FooBar> blabla;
public void setBlabla(HashMap<String, FooBar> blabla) {
this.blabla = blabla;
}
public HashMap<String, FooBar> getBlabla() {
return blabla;
}
};
public class App {
static String target = ""
+ "{"
+ " \"blabla\": {"
+ " \"1\": {"
+ " \"foo\": \"foo1\","
+ " \"bar\": \"bar1\""
+ " },"
+ " \"22\": {"
+ " \"foo\": \"foo22\","
+ " \"bar\": \"bar22\""
+ " }"
+ " }"
+ "}";
public static void main(String[] args) throws Exception {
FooBarObject blabla = new FooBarObject();
HashMap map = new HashMap<String, FooBar>();
map.put("1", new FooBar());
map.put("22", new FooBar());
blabla.setBlabla(map);
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(blabla);
System.out.println("--- BEGIN ---");
System.out.println(json);
System.out.println("--- END ---");
blabla = mapper.readValue(target, FooBarObject.class);
System.out.println("--- BEGIN ---");
for ( Map.Entry<String, FooBar> entry : blabla.blabla.entrySet() ) {
String internal = mapper.writeValueAsString(entry.getValue());
System.out.println(entry.getKey() + ": " + internal);
}
System.out.println("--- END ---");
}
}
吗?
Array