从JSON深入获取价值 [英] Getting a value from deep inside JSON
问题描述
我正在连接到第三方API,并获取了很长的JSON字符串.我只需要一个值,但是它位于层次结构的深处.有没有一种简单的方法就可以完成整个过程?我环顾四周,但似乎没有轻松的事情.
I am connecting to a third party API and getting back a long JSON string. I only need one value from it, but it is located pretty deep inside the hierarchy. Is there a simple way to get it, without going through the whole thing? I looked all over but nothing seems easy.
这是我的示例:
"response":{"status":1,"httpStatus":200,"data":{"myDesiredInfo":"someInfo"},"errors":[],"errorMessage":null}}
我一直在尝试使用Gson,因此我可以将此Blob作为JsonObject获得.我确定有一些简单的东西,像这样:
I've been trying to use Gson so I can get this blob as a JsonObject. I was sure there's something simple, like this:
jsonObject.get("myDesiredInfo")
或至少是这样的:
jsonObject.get("response.data.myDesiredInfo")
但是它似乎不存在.
那么有没有可以让我做到这一点的解析器?
So is there any parser out there that will allow me to do this?
推荐答案
这是我的json字符串
This is my json string
String s="{"age":0,"name":"name","email":"emailk","address":{"housename":"villa"}}";
我使用以下代码获取房屋名称
I use following code to get housename
JsonElement je = new JsonParser().parse(s);
JsonObject asJsonObject = je.getAsJsonObject();
JsonElement get = asJsonObject.get("address");
System.out.println(s + "\n" + get);
JsonObject asJsonObject1 = get.getAsJsonObject();
JsonElement get1 = asJsonObject1.get("housename");
System.out.println(get1);
以下是我的输出:
{"age":0,"name":"name","email":"emailk","address":{"housename":"villa"}}
{"housename":"villa"}
"villa"
我认为没有其他方法可以做到这一点.我还尝试了其他方式,但没有得到任何输出.
I don't think there is another way to do this. I also tried to do in other ways but i didn't get any output.
这篇关于从JSON深入获取价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!