【发布时间】:2014-10-20 02:58:55
【问题描述】:
我有一个字符串形式的 Json 请求:-
{
"insertDataRequest": [
{
"id": "98",
"name": "Mercer Island",
"age": "12",
"designation": "SSE"
}
]
}
现在,我需要将此字符串格式转换为 Java 对象并使用 Jackson 检索它的值...
到目前为止,我做了以下事情:-
public static void main(String[] args) throws IOException
{
ObjectMapper objectMapper = new ObjectMapper();
String json= "{\"insertDataRequest\":{\"id\":98, \"name\":\"Mercer Island\",\"age\":12,\"designation\":\"SEE\"}}";
JsonNode root2 = objectMapper.readTree(json);
JsonNode rootnode = root2.get("insertDataRequest");
if (rootnode != null && rootnode.has("id")) {
int id = rootnode.get("id").intValue();
System.out.println(id);
}
if (rootnode != null && rootnode.has("name")) {
String name = rootnode.get("name").toString().replace("\"", "");
System.out.println(name);
}
if (rootnode != null && rootnode.has("age")) {
int age = rootnode.get("age").intValue();
System.out.println(age);
}
if (rootnode != null && rootnode.has("designation")) {
String designation = rootnode.get("designation").toString().replace("\"", "");
System.out.println(designation);
}
}
现在..我在运行代码时没有得到任何值..如何转换这个字符串并检索值..我错过了什么???请帮忙....
【问题讨论】:
-
使用你的调试器,检查变量。请注意,insertDataRequest 属性是一个对象的 array。不是对象。
-
如果我从请求中删除 '[' 我能够获取值 .. 但我需要 '[' ...因为值可以重复 .. 我怎样才能使用 '[ ' ...
-
阅读JsonNode的javadoc。找到允许在索引 0 处获取元素的方法。fasterxml.github.io/jackson-databind/javadoc/2.3.0/com/…
-
我已经搜索了整个网络..但没有找到任何合适的方法来迭代给定格式的请求..请帮助我获得迭代和获取值的方法跨度>
-
那是你的错误。你不应该在网上到处搜索。您应该阅读 JsonNode 的 javadoc 以了解如何使用它,并访问索引 0 处的元素。
标签: java json rest parsing jackson