简体   繁体   English

如何在Java中解析未知的JSON结构

[英]How to parse unknown JSON structure in Java

I have this bit of code: 我有这段代码:

JSONArray data = object.getJSONArray("Test");

for (int i = 0; i < data.length(); i++)
{
    JSONObject dataObject = data.getJSONObject(i);
    etc ...

I don't know before run time what I will have in dataObject though. 我不知道在运行之前,我将在dataObject中拥有什么。 Is it possible to loop through the keys somehow? 是否有可能以某种方式遍历键?

I thought this might work, as I saw it mentioned in another Stackoverflow article: 我认为这可能有效,正如我在另一篇Stackoverflow文章中提到的那样:

for (String key : dataObject.keys())

But I get an error saying "Can only iterate over an array or an instance of java.lang.Iterable" 但是我收到一条错误消息:“只能迭代数组或java.lang.Iterable的实例”

Does anyone know how it can be done? 有谁知道该怎么做?

To Retrieving the keys of your object this might work : 要检索对象的键,这可能会起作用:

Iterator<?> iterator = object.keys();
while (iterator.hasNext()) {
   String key = (String)iterator.next();
   //do what you want with the key.                 
}  

I hope this will help 我希望这个能帮上忙

Object obj = parser.parse(s);
JSONArray array = (JSONArray)obj;

Refer below link 参考以下链接

http://json.org/java/ http://json.org/java/

http://www.tutorialspoint.com/json/json_java_example.htm http://www.tutorialspoint.com/json/json_java_example.htm

i guess 我猜

Iterator keys = json.keys(); 迭代器键= json.keys();

this will give you the keys of your json object as java iterator 这将为您提供json对象的键,作为java迭代器

How can I iterate JSONObject to get individual items 我如何迭代JSONObject以获得单个项目

This will give you an idea to get the keys and values in iterative manner and helps you to implement for your need 这将为您提供一个以迭代方式获取键和值的想法,并帮助您根据需要实施

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM