【问题标题】:Dynamic Json File for Java ObjectsJava 对象的动态 Json 文件
【发布时间】:2021-08-13 14:25:27
【问题描述】:

我有一个 java 类模型,它具有 getter/setter 方法以及枚举类型。 我想公开 JSON 文件以及所有字段,默认情况下一个字段有值,其他字段为空。

如何使用 java 模型类创建动态文件。

package com.manifest;

import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.annotation.JsonValue;

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
   "@id",
   "@type",
   "dct:identifier"
})
@Generated("jsonschema2pojo")
public class DctMediaType {

/**
 * 
 * (Required)
 * 
 */
@JsonProperty("@id")
private String id;
/**
 * 
 * (Required)
 * 
 */
@JsonProperty("@type")
private DctMediaType.Type type;
@JsonProperty("dct:identifier")
private String dctIdentifier;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();

/**
 * 
 * (Required)
 * 
 */
@JsonProperty("@id")
public String getId() {
    return id;
}

/**
 * 
 * (Required)
 * 
 */
@JsonProperty("@id")
public void setId(String id) {
    this.id = id;
}

public DctMediaType withId(String id) {
    this.id = id;
    return this;
}

/**
 * 
 * (Required)
 * 
 */
@JsonProperty("@type")
public DctMediaType.Type getType() {
    return type;
}

/**
 * 
 * (Required)
 * 
 */
@JsonProperty("@type")
public void setType(DctMediaType.Type type) {
    this.type = type;
}

public DctMediaType withType(DctMediaType.Type type) {
    this.type = type;
    return this;
}

@JsonProperty("dct:identifier")
public String getDctIdentifier() {
    return dctIdentifier;
}

@JsonProperty("dct:identifier")
public void setDctIdentifier(String dctIdentifier) {
    this.dctIdentifier = dctIdentifier;
}

public DctMediaType withDctIdentifier(String dctIdentifier) {
    this.dctIdentifier = dctIdentifier;
    return this;
}

@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
    return this.additionalProperties;
}

@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
    this.additionalProperties.put(name, value);
}

public DctMediaType withAdditionalProperty(String name, Object value) {
    this.additionalProperties.put(name, value);
    return this;
}

@Override
public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append(DctMediaType.class.getName()).append('@').append(Integer.toHexString(System.identityHashCode(this))).append('[');
    sb.append("id");
    sb.append('=');
    sb.append(((this.id == null)?"<null>":this.id));
    sb.append(',');
    sb.append("type");
    sb.append('=');
    sb.append(((this.type == null)?"<null>":this.type));
    sb.append(',');
    sb.append("dctIdentifier");
    sb.append('=');
    sb.append(((this.dctIdentifier == null)?"<null>":this.dctIdentifier));
    sb.append(',');
    sb.append("additionalProperties");
    sb.append('=');
    sb.append(((this.additionalProperties == null)?"<null>":this.additionalProperties));
    sb.append(',');
    if (sb.charAt((sb.length()- 1)) == ',') {
        sb.setCharAt((sb.length()- 1), ']');
    } else {
        sb.append(']');
    }
    return sb.toString();
}

@Override
public int hashCode() {
    int result = 1;
    result = ((result* 31)+((this.id == null)? 0 :this.id.hashCode()));
    result = ((result* 31)+((this.dctIdentifier == null)? 0 :this.dctIdentifier.hashCode()));
    result = ((result* 31)+((this.additionalProperties == null)? 0 :this.additionalProperties.hashCode()));
    result = ((result* 31)+((this.type == null)? 0 :this.type.hashCode()));
    return result;
}

@Override
public boolean equals(Object other) {
    if (other == this) {
        return true;
    }
    if ((other instanceof DctMediaType) == false) {
        return false;
    }
    DctMediaType rhs = ((DctMediaType) other);
    return (((((this.id == rhs.id)||((this.id!= null)&&this.id.equals(rhs.id)))&&((this.dctIdentifier == rhs.dctIdentifier)||((this.dctIdentifier!= null)&&this.dctIdentifier.equals(rhs.dctIdentifier))))&&((this.additionalProperties == rhs.additionalProperties)||((this.additionalProperties!= null)&&this.additionalProperties.equals(rhs.additionalProperties))))&&((this.type == rhs.type)||((this.type!= null)&&this.type.equals(rhs.type))));
}

@Generated("jsonschema2pojo")
public enum Type {

    DCT_MEDIA_TYPE("dct:MediaType");
    private final String value;
    private final static Map<String, DctMediaType.Type> CONSTANTS = new HashMap<String, DctMediaType.Type>();

    static {
        for (DctMediaType.Type c: values()) {
            CONSTANTS.put(c.value, c);
        }
    }

    Type(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return this.value;
    }

    @JsonValue
    public String value() {
        return this.value;
    }

    @JsonCreator
    public static DctMediaType.Type fromValue(String value) {
        DctMediaType.Type constant = CONSTANTS.get(value);
        if (constant == null) {
            throw new IllegalArgumentException(value);
        } else {
            return constant;
        }
    }

}

}

需要我的 JSON 输出文件,如下所示:

{
 "@id":null,
 "@type":"dct:MediaType"
 "dct:identifier":null
}

我尝试了以下方式,但我得到了空的 json 对象 {}。

ObjectMapper dynamicMapper = new ObjectMapper();
 dynamicMapper.enable(SerializationFeature.INDENT_OUTPUT);
 dynamicMapper.setSerializationInclusion(Include.ALWAYS);
 String jsonValue = dynamicMapper.writeValueAsString(new DctMediaType());

请提供一些创建动态 json 文件创建的指导。

【问题讨论】:

    标签: java json serialization dynamic objectmapper


    【解决方案1】:

    问题是你们都有 @JsonInclude(JsonInclude.Include.NON_NULL) 注释,它告诉序列化程序跳过任何 NULL 值并从 JSON 输出中删除属性,并且您永远不会将字段初始化为 bean 中的任何非 null 值.

    您将new DctMediaType() 传递给映射器,但从未设置任何字段。

    听起来如果您想要 JSON 中的空值,那么您应该将注释更改为@JsonInclude(JsonInclude.Include.ALWAYS)

    【讨论】:

    • 以上类从Json模式动态生成,我们不能覆盖模型类中的json注解。如果我们改变 json 模式,上面的类会自动生成更新的属性。
    【解决方案2】:

    通过使用下面的代码,我可以为我的用例实现解决方案。

    Class<?> clazzObj = Class.forName("com.manifest.DctMediaType");
                    JsonObject tempObj = new JsonObject();
                    for (Field newField : clazzObj.getDeclaredFields()) {
                        if (newField.isAnnotationPresent(JsonProperty.class)) {
                            String annotationValue = newField.getAnnotation(JsonProperty.class).value();
                            String childTypeString = newField.getGenericType().toString();                          
                                tempObj.add(annotationValue, "");
    
                            }
                          }
    

    我的输出:

     {
        "@id": "",
        "@type": "dct:MediaType",
        "dct:identifier": ""
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-08-20
      • 1970-01-01
      • 2020-06-18
      • 1970-01-01
      • 1970-01-01
      • 2022-08-02
      • 2012-11-20
      相关资源
      最近更新 更多