简体   繁体   English

从 java 中的 POST 读取 json 文件

[英]Read json file from POST in java

How can I unmarhsaller json file like this?我怎样才能解开这样的 json 文件?

{
    "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我有一个 class 可以很好地与 packageId、jsScript、functionName 配合使用,但不能与测试配合使用

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我也尝试阅读像 String 这样的测试,但没有帮助

It seems that you have encountered some problems for deserializing the JSON array tests to objects.您似乎在将 JSON 数组tests反序列化为对象时遇到了一些问题。 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" .在您的 class Tests中添加@JsonIgnoreProperties(ignoreUnknown = true)以防止您的代码出现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.反序列化 JSON 数组testsList<JsonNode>如果它不重要并且您将来不会进一步解析它。

Method 3方法三
Use follwing class for mapping JSON array tests to List<Test> .使用以下 class 将 JSON 数组tests映射到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.顺便说一句,我认为您不需要使用@JsonCreator进行反序列化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM