用于递归结构的json解析器 [英] json parser for recursive structure

查看:140
本文介绍了用于递归结构的json解析器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

We have to parse a json structure similar to below.

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。

The issue is, cmp element is present in the json infinitly (and it is recursive too). The cmp element contains lots of properties other than name, id and desc. But we need only name, id and desc to extract from the jSON.

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

I can able to parse the JSON string using com.json.parsers.JSONParser. But populating the parsed JSON to a model class/bean class is not working. It may be a simple logic. But I cannot. Please help...

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

The json file is generated as an output of one modeling software.

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

I want to parse this, using java. Can somebody help me to parse this?

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

Hope I have explained the issue correctly. Your help will be helpful for us.

推荐答案

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

You can do this with Jackson, just create your object with all the fields that may or may not be present in the message. All the fields not present in the message will end up as null (or default value for primitives) in the resulting object.

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

Just have the object contain a copy of itself and that will handle the recursion

@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
}

这篇关于用于递归结构的json解析器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆