将复杂的JSON反序列化为Java,嵌套多个级别的类

时间:2016-11-29 09:43:32

标签: java json jackson inner-classes json-deserialization

我正在尝试将Cucumber的Json输出转换为单个Java对象。这包含嵌套四层深度的对象,我无法反序列化它。我现在正在使用杰克逊,但愿意接受建议。 这是我的Json代码:

{
"line": 1,
"elements": [
  {
    "line": 3,
    "name": "Converteren centimeters naar voeten/inches",
    "description": "",
    "id": "applicatie-neemt-maten-in-cm-en-converteert-ze-naar-voet/inch,-en-vice-versa;converteren-centimeters-naar-voeten/inches",
    "type": "scenario",
    "keyword": "Scenario",
    "steps": [
      {
        "result": {
          "duration": 476796588,
          "status": "passed"
        },
        "line": 4,
        "name": "maak Maten-object aan met invoer in \"centimeters\"",
        "match": {
          "arguments": [
            {
              "val": "centimeters",
              "offset": 37
            }
          ],
          "location": "StepDefinition.maakMatenObjectAanMetInvoerIn(String)"
        },
        "keyword": "Given "
      },
      {
        "result": {
          "duration": 36319,
          "status": "passed"
        },
        "line": 5,
        "name": "ik converteer",
        "match": {
          "location": "StepDefinition.converteerMaten()"
        },
        "keyword": "When "
      },
      {
        "result": {
          "duration": 49138,
          "status": "passed"
        },
        "line": 6,
        "name": "uitvoer bevat maat in \"voeten/inches\"",
        "match": {
          "arguments": [
            {
              "val": "voeten/inches",
              "offset": 23
            }
          ],
          "location": "StepDefinition.uitvoerBevatMaatIn(String)"
        },
        "keyword": "Then "
      }
    ]
  },
  {
    "line": 8,
    "name": "Converteren voeten/inches naar centimeters",
    "description": "",
    "id": "applicatie-neemt-maten-in-cm-en-converteert-ze-naar-voet/inch,-en-vice-versa;converteren-voeten/inches-naar-centimeters",
    "type": "scenario",
    "keyword": "Scenario",
    "steps": [
      {
        "result": {
          "duration": 84175,
          "status": "passed"
        },
        "line": 9,
        "name": "maak Maten-object aan met invoer in \"voeten/inches\"",
        "match": {
          "arguments": [
            {
              "val": "voeten/inches",
              "offset": 37
            }
          ],
          "location": "StepDefinition.maakMatenObjectAanMetInvoerIn(String)"
        },
        "keyword": "Given "
      },
      {
        "result": {
          "duration": 23928,
          "status": "passed"
        },
        "line": 10,
        "name": "ik converteer",
        "match": {
          "location": "StepDefinition.converteerMaten()"
        },
        "keyword": "When "
      },
      {
        "result": {
          "duration": 55547,
          "status": "passed"
        },
        "line": 11,
        "name": "uitvoer bevat maat in \"centimeters\"",
        "match": {
          "arguments": [
            {
              "val": "centimeters",
              "offset": 23
            }
          ],
          "location": "StepDefinition.uitvoerBevatMaatIn(String)"
        },
        "keyword": "Then "
      }
    ]
  }
],
"name": "Applicatie neemt maten in cm en converteert ze naar voet/inch, en vice versa",
"description": "",
"id": "applicatie-neemt-maten-in-cm-en-converteert-ze-naar-voet/inch,-en-vice-versa",
"keyword": "Feature",
"uri": "sample.feature"
}

我尝试了很多不同的方法。首先我使用了嵌套的内部类,但是看起来你必须让它们成为静态的,我担心这样做是不行的,因为我在同一个对象中有多个实例(例如,根中有多个“元素” - 对象)。然后我尝试将它们放在单独的类中,使用Json注释。这就是让我(省略setters)的地方:

public class CucumberUitvoer {
    private String name;
    private String description;
    private String id;
    private String keyword;
    private String uri;
    private int line;
    @JsonProperty("elements")
    private List<FeatureObject> elements;

    public CucumberUitvoer(){}
}

public class FeatureObject {
    private String name;
    private String description;
    private String id;
    private String type;
    private String keyword;
    private int line;
    @JsonProperty("steps")
    private List<StepObject> steps;

    public FeatureObject() {
    }
}

public class StepObject {
    @JsonProperty("result")
    private ResultObject result;
    private String name;
    private String given;
    private String location;
    private String keyword;
    private int line;
    @JsonProperty("match")
    private MatchObject match;

    public StepObject(){}
}

public class ResultObject {
    private int duration;
    private String status;

    public ResultObject(){}
}

public class MatchObject {
    @JsonProperty("arguments")
    private List<ArgumentObject> arguments;
    private String location;

    public MatchObject(){}
}

public class ArgumentObject {
    private String val;
    private String offset;

    public ArgumentObject(){}
}

为了澄清,here是嵌套如何工作的类图。

此解决方案给出了以下错误:

com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of nl.icaprojecten.TestIntegratieQuintor.JSONInterpreter.CucumberUitvoer out of START_ARRAY token

以下是执行实际映射的代码:

ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    CucumberUitvoer obj1 = null;
    try {
        obj1 = mapper.readValue(json, CucumberUitvoer.class);
    } catch (IOException e) {
        e.printStackTrace();
    }

是否可以快速修复此方法以使其正常工作,还是应该尝试完全不同的方法?

3 个答案:

答案 0 :(得分:2)

好的我花了一些时间调试并试图弄清问题是什么,最后是非常明显的。

implements Serializable

这就是我添加到MatchObject并运行的行。

当我们首先尝试反序列化某个对象时,我们必须使这些类实现接口Serializable

答案 1 :(得分:1)

我刚试过你的示例代码,奇怪的是,它有效。

如果JSON按照提供的方式进入并且getter,setter,构造函数实际存在,那么请你仔细检查你的导入吗?

答案 2 :(得分:-1)

您可以从此代码中获取反序列化的想法,

public class testCustomDeSerializer extends JsonDeserializer<test> {

public testCustomDeSerializer() {
    this(null);
}

public TestCustomDeSerializer(Class t) {
   // super(t);
}

@Override
public Test deserialize(JsonParser p, DeserializationContext ctx) throws IOException, JsonProcessingException {
    ObjectCodec objectCodec = p.getCodec();
    JsonNode node = objectCodec.readTree(p);

    ObjectMapper objectMapper =  new ObjectMapper();
    Test test= new Test();


    test.setId(node.get("line").asText());

    List<elements> elementList = new ArrayList<>();
    JsonNode elementsNode = node.get("elements");
    Iterator<JsonNode> slaidsIterator = elementsNode.elements();
    while (slaidsIterator.hasNext()) {
        Steps steps= new Steps();
        JsonNode slaidNode = slaidsIterator.next();
        JsonNode stepNode= (JsonNode) slaidNode.get("Steps");
        BoundingPoly in = objectMapper.readValue(stepNode.toString(), Steps.class);
        elementsNode.setSteps(in);
        /// continue

 return
        }

希望有所帮助