json parser for recursive structure

2019-01-29 03:16发布

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.

2条回答
一夜七次
2楼-- · 2019-01-29 03:43

Take a look at Google Gson library. With it you can do things like:

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
查看更多
闹够了就滚
3楼-- · 2019-01-29 03:46

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
}
查看更多
登录 后发表回答