java Jackson 解析器 json setter 将值作为字符串数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16924155/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 00:24:10  来源:igfitidea点击:

Hymanson parser json setter to take value as string array

javajsonHymansongson

提问by javaMan

I have below json:

我有以下json:

    "[{\"movieName\":\"A\",\"Leadactor\":\"\",\"leadActress\":\"\",\"movieTitle\":\"\",\"hero\":\"\",\"heroine\":\"\",\"source\":\"IMDB\"}," +
    "{\"movieName\":\"\",\"Leadactor\":\"\",\"leadActress\":\"\",\"movieTitle\":\"B\",\"hero\":\"B1\",\"heroine\":\"B2\",\"source\":\"Netflix\"}," +
    "{\"movieName\":\"C\",\"Leadactor\":\"C1\",\"leadActress\":\"C2\",\"movieTitle\":\"\",\"hero\":\"\",\"heroine\":\"\",\"source\":\"IMDB\"}," +
    "{\"movieName\":\"D\",\"Leadactor\":\"D1\",\"leadActress\":\"D2\",\"movieTitle\":\"\",\"hero\":\"\",\"heroine\":\"\",\"source\":\"IMDB\"}," +
    "{\"movieName\":\"\",\"Leadactor\":\"\",\"leadActress\":\"\",\"movieTitle\":\"E\",\"hero\":\"E1\",\"heroine\":\"E2\",\"source\":\"Netflix\"}]";

I am using Hymanson parser to map it to a class:

我正在使用 Hymanson 解析器将它映射到一个类:

I want movieName and movieTitle to map into Name property in the java class. So i wrote the below class:

我希望 movieName 和 movieTitle 映射到 java 类中的 Name 属性。所以我写了下面的类:

public static class MovieData {
    @JsonProperty("Name")
    private String name;

    @JsonSetter({"movieName"})
    private void setMovieName(final String name) {
            if((name != null) && (! name.equals(""))) {
                    setNameInternal(name);
            }
    }

    @JsonSetter("movieTitle")
    private void setMovieTitle(final String name) {
            if((name != null) && (! name.equals(""))) {
                    setNameInternal(name);
            }
    }

    private void setNameInternal(final String name) {
            this.name = name;
    }

}

}

In my real json there are so many fields like movieName, movieTitle which i want to normalize into a common name.

在我真正的 json 中有很多字段,如 movieName、movieTitle,我想将它们规范化为一个通用名称。

Is there any simple syntax like the below which can reduce code duplication:

有没有像下面这样的简单语法可以减少代码重复:

public static class MovieData {
    @JsonProperty("Name")
    private String name;

 @JsonSetter(value = { "movieName", "movieTitle" })
 private void setName(final String name) {
        if((name != null) && (! name.equals(""))) {
                this.name=name;
        }
}
  }

The above code gave me error on jsonSetter:

上面的代码在 jsonSetter 上给了我错误:

 Type mismatch: cannot convert from String[] to String.

EDIT

编辑

If Hymanson doesn't support it, can GSON Support this operation.

如果 Hymanson 不支持,GSON 可以支持这个操作。

Thanks

谢谢

采纳答案by Micha? Ziober

You can use @JsonAnySetter, what it is mean you can find on Hymanson Core (Data-Binding) Annotationspage.

您可以使用@JsonAnySetter,这意味着您可以在Hymanson Core (Data-Binding) Annotations页面上找到。

I have created simple bean which is related to your example:

我创建了与您的示例相关的简单 bean:

class MovieData {

    private static List<String> NAME_PROPERTIES = Arrays.asList("movieName", "movieTitle");

    private String name;

    public void setName(String name) {
        this.name = name;
    }

    @JsonAnySetter
    private void parseUnknownProperties(String propertyName, String propertyValue) {
        if (NAME_PROPERTIES.contains(propertyName) && !propertyValue.isEmpty()) {
            this.name = propertyValue;
        }
    }

    @Override
    public String toString() {
        return name;
    }
}

Now when I deserialize your JSON in this way:

现在,当我以这种方式反序列化您的 JSON 时:

ObjectMapper objectMapper = new ObjectMapper();
System.out.println(Arrays.toString(objectMapper.readValue(json, MovieData[].class)));

As result I can see:

结果我可以看到:

[A, B, C, D, E]

回答by Ingreatway

Dont do this much. it is very simple with Gson

不要做这么多。使用 Gson 非常简单

create class for your single set record like

为您的单组记录创建类

class Movie{
    private String movieName;
    private String Leadactor;
    private String leadActress;

    //put getter and setter for your fields
}

in main file
Type type = new TypeToken<List<Movie>>(){}.getType();
List<Movie> data = new Gson().fromJson(json_string,type);

回答by Eugene Petrenko

You declare the field like @JsonProperty String[] data

你像这样声明这个领域 @JsonProperty String[] data

and use

并使用

 new ObjectMapper()
      .enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
      .readValue(json, YOUT_TYPE.class)

So this option make Hymanson part both "foo":"bar" and "foo": ["a", "b", "c"].

所以这个选项让Hyman逊同时成为“foo”:“bar”和“foo”:[“a”,“b”,“c”]。

All you need to do is to merge string array back into the string with right line separators. I do it via Guava data == null ? null : Jointer.on("\n").join(data)

您需要做的就是使用正确的行分隔符将字符串数组合并回字符串。我是通过番石榴做的data == null ? null : Jointer.on("\n").join(data)