Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
686 views
in Technique[技术] by (71.8m points)

java - json parser for recursive structure

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 = "";        
          }
        }       
    }
}

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.

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...

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...