java - 用于递归结构的json解析器

标签 java json parsing recursion

我们必须解析类似于下面的 json 结构。

project {
   header {
   }
   pool {
   }
   cmp {
      name = "";
      id = "";
      desc = "";
      cmp [
        {
          name = "";
          id = "";
          desc = "";
        }
        {
          name = "";
          id = "";
          desc = "";
        }
        {
          name = "";
          id = "";
          desc = "";
          cmp [
          {
            name = "";
            id = "";
            desc = "";        
          }
        }       
    }
}

问题是,cmp 元素无限存在于 json 中(而且它也是递归的)。 cmp 元素包含许多除 name、id 和 desc 之外的属性。但我们只需要从 jSON 中提取 name、id 和 desc。

我可以使用 com.json.parsers.JSONParser 解析 JSON 字符串。但是将解析的 JSON 填充到模型类/bean 类是行不通的。这可能是一个简单的逻辑。但是我不能。请帮助...

json 文件是作为一个建模软件的输出生成的。

我想用 java 解析这个。有人可以帮我解析吗?

希望我已经正确解释了这个问题。您的帮助将对我们有所帮助。

最佳答案

您可以使用 Jackson 执行此操作,只需使用消息中可能存在或不存在的所有字段创建您的对象。消息中不存在的所有字段在生成的对象中都将以 null(或原语的默认值)结束。

只需让对象包含其自身的副本,这将处理递归

@XmlRootElement
public class Foo {
   Foo recursiveFoo; // will be null or another instance of Foo
   int intData; // Will be 0 or an integer value
   String strData; // Will be null or a String value

   // Getters and setters here
}

关于java - 用于递归结构的json解析器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20635220/

相关文章:

json - 使用 Swift 4 Decodable 解析具有混合属性值的 JSON

javascript - 使用 jQuery 或 Javascript 搜索嵌套 JSON

c++ - 使用 boost::spirit 匹配单词

java - 用于名字验证的正则表达式

java - 如何快速初始化char二维数组?

java - 如果用户在注册时没有从图库中选择任何照片,我如何提醒用户?

c++ - 多个定义?

java - 如何用java制作一个在每个问题之前播放声音的测验?

javascript - 如何根据日期属性之间的范围是否包含给定日期来过滤对象数组?

javascript - Jquery和ajax与json数据解析