我想使用Jackson创建简单的JSON对象,我不需要为每个响应构建自定义类,而是一个类似于下面代码的预制对象.其他JSON库(android,JSON.org,GSON)你可以做类似的事情
JsonObject myObject = new JsonObject("{\"a\":1}");
myObject.getInt("a"); // returns 1
Run Code Online (Sandbox Code Playgroud)
我似乎无法在Jackson套餐中找到类似的操作.PS:我知道我可以创建一个java类来封装这个特定的JSON字符串,但我正在寻找的是一种创建通用JSON对象的方法,我不需要将其解析为我定义的类.我似乎无法在互联网上找到任何指向类似于此的东西.我有一种感觉,这是在Jacksons领域之外,他们不支持这样的操作.如果是这种情况就这么说,我将结束这个问题.
我的目标是在我的项目中没有另一个Json库.
编辑2014:我发现您可以使用org.codehaus.jackson.node.ObjectNode将保留您的对象的类,并允许您按我的问题中所述进行操作.
下面是代码示例:
ObjectMapper mapper = new ObjectMapper();
ObjectNode myObject = (ObjectNode) mapper.readTree("{\"a\":1}");
System.out.println(myObject.get("a").asInt()); // prints 1
Run Code Online (Sandbox Code Playgroud)
在我看来你需要一个Map. 如果您有一个简单的 JSON 结构,那么您可以使用Map<String, String>如下所示:
String json = "{\"name\":\"mkyong\", \"age\":\"29\"}";
Map<String,String> map = new HashMap<String,String>();
ObjectMapper mapper = new ObjectMapper();
try {
//convert JSON string to Map
map = mapper.readValue(json,
new TypeReference<HashMap<String,String>>(){});
System.out.println(map);
} catch (Exception e) {
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
如果您有一个更复杂的 JSON 结构,其中包含嵌套对象等,那么您可以使用Map<String, Object>:
ObjectMapper mapper = new ObjectMapper();
// read JSON from a file
Map<String, Object> map = mapper.readValue(
new File("c:\\user.json"),
new TypeReference<Map<String, Object>>() {
});
System.out.println(map.get("name"));
System.out.println(map.get("age"));
@SuppressWarnings("unchecked")
ArrayList<String> list = (ArrayList<String>) map.get("messages");
Run Code Online (Sandbox Code Playgroud)
示例取自有用的Mkyong.com。
| 归档时间: |
|
| 查看次数: |
4066 次 |
| 最近记录: |