0

How can I unmarhsaller json file like this?

{ "packageId": "11", "jsScript": "var divideFn = function(a,b) { return a/b} ", "functionName": "divideFn", "tests": [ { "testName": "test1", "expectedResult": "2.0", "params": [ 2, 1 ] } ] } 

I have a class that works well with packageId, jsScrript, functionName, but not with the tests

public class Data { private final int packageId; private final String jsScript; private final String functionName; private final List<Tests> tests; @JsonCreator public Data(@JsonProperty("packageId") String packageId, @JsonProperty("jsScript") String jsScript, @JsonProperty("functionName") String functionName, @JsonProperty("tests") List<Tests> tests) { this.packageId = Integer.parseInt(packageId); this.jsScript= jsScript; this.functionName = functionName; this.tests = tests; } } public class Tests{ public final String testName; public final int expectedResult; @JsonCreator public Tests(@JsonProperty("testName") String testName, @JsonProperty("expectedResult") String expectedResult){ this.testName= testName; this.expectedResult = Integer.parseInt(expectedResult); } } 

What should I change in classes to make it work well? I also tried to read tests like String, but it didn't help

5
  • What error are you getting? Commented Nov 1, 2019 at 15:08
  • @VikramV When I am trying to make a POST request I get Cannot unmarshal JSON as Data Commented Nov 1, 2019 at 15:23
  • 2
    Please post the error. If I had to guess, it would be because there's no @JsonProperty for params. Commented Nov 1, 2019 at 15:40
  • 1
    The code that triggers the unmarshalling would also be helpful. Please add it to the question. Commented Nov 1, 2019 at 16:28
  • I think your Test class is missing params attribute. Either add the field or add @JsonIgnoreProperties(ignoreUnknown = true) at Tests class level. Commented Nov 1, 2019 at 16:38

1 Answer 1

1

It seems that you have encountered some problems for deserializing the JSON array tests to objects. There are several methods to solve this.

Method 1
Add @JsonIgnoreProperties(ignoreUnknown = true) on your class Tests to prevent your code from the exception of Unrecognized field "params".

Method 2
Deserialize JSON array tests to List<JsonNode> if it is not important and you won't further parse it in the future.

Method 3
Use follwing class for mapping JSON array tests to List<Test>.

class Test { private String testName; private Float expectedResult; private List<Integer> params; //general getters ans setters } 

BTW, I don't think you need to use @JsonCreator for deserialization.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.