【问题标题】:json parser for recursive structure用于递归结构的json解析器
【发布时间】:2014-01-05 06:40:30
【问题描述】:

我们必须解析一个类似于下面的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 之外的许多属性。但我们只需要 name、id 和 desc 即可从 JSON 中提取。

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

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

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

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

【问题讨论】:

  • 你是否已经正确解析了第一级?
  • 是的。我正在使用 com.json.parsers.JSONParser 来解析 JSON 字符串。我的死锁是 cmd 的递归并且只从 cmd 中提取很少的属性。
  • 您知道您的示例不是 json 吗?假设您实际上有 json,您是否查看过诸如 Jackson 和 GSON 之类的 JSON 库?你还尝试了什么?
  • 它只是 JSON 字符串。我可以使用 com.json.parsers.JSONParser 解析 JSON 字符串。但是将解析的 JSON 填充到模型类/bean 类是行不通的。这可能是一个简单的逻辑。但是我不能。请帮助...感谢您的快速回复..

标签: java json parsing recursion


【解决方案1】:

您可以使用 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
}

【讨论】:

    【解决方案2】:

    看看Google Gson 库。有了它,您可以执行以下操作:

    class BagOfPrimitives {
      private int value1 = 1;
      private String value2 = "abc";
      private transient int value3 = 3;
      BagOfPrimitives() {
        // no-args constructor
      }
    }
    
    //(Serialization)
    BagOfPrimitives obj = new BagOfPrimitives();
    Gson gson = new Gson();
    String json = gson.toJson(obj); 
    //==> json is {"value1":1,"value2":"abc"}
    
    
    //(Deserialization)
    BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);  
    //==> obj2 is just like obj
    

    【讨论】:

    • 但是为了使用Gson,我们需要创建模型类BagOfPrimitives,它包含JSON结构中的所有属性,对吧?在我的 JSON 中,有时某些元素可能不会出现在 cmd 中。
    • 这不是问题。假设你有:class BagOfPrimitives { private int value1; private String value2; private int value3; BagOfPrimitives() { // no-args constructor } },你的 json 是:{"value1":1}。您仍然可以将对象反序列化到您的类中,只是缺少的值将设置为默认值 (int:0, String: null)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-31
    • 2018-05-16
    相关资源
    最近更新 更多