java - 如何从具有自定义值的类字段创建 Json 数组?

标签 java json jackson

我想生成一个关于配置类字段的 JSON 数组(配置)。我想要做的是如果某个字段为 true,则将其自定义预定义值添加到 JSON 数组。

如何使用这些值创建 JSON 数组?

public class Configuration{
    private Boolean width;
    private Boolean height;
    private Boolean isValid;

    //Getters and setters
}

例如,如果所有字段都为 true,我想生成一个 JSON 数组,例如;

String configuration = "['valid', {'height' : 768}, {'width' : 1024}, {'align': []}]";

如果仅 isValid 和 height 为 true;

String configuration = "['valid', {'height' : 768}]";

到目前为止我做了什么;

String configuration = "["; 

if(width){
    configuration += "{'width' : 1024}, ";
}

if(height){
    configuration += "{'height' : 768}, ";
}

if(align){
    configuration += "{'align' : []}, ";
}

....//After 40 fields

configuration += "]";

最佳答案

在这种情况下,我发现编写注释并使用反射很有用。 下面是一个简单的例子。您还可以将其与 VPK 建议的 JsonArray 结合起来。

JsonArrayMember.java -- 我们使用的注释

package org.stackoverflow.helizone.test;

import java.lang.annotation.*;

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface JsonArrayMember {
    public String value();
}

Configuration.java -- Configuration 类,其字段用 @JsonArrayMember 注解

package org.stackoverflow.helizone.test;

public class Configuration {

    @JsonArrayMember("{width: 1024}")
    private Boolean width;

    @JsonArrayMember("{height: 768}")
    private Boolean height;

    @JsonArrayMember("'valid'")
    private Boolean isValid;

    public Boolean getWidth() {
        return width;
    }

    public void setWidth(Boolean width) {
        this.width = width;
    }

    public Boolean getHeight() {
        return height;
    }

    public void setHeight(Boolean height) {
        this.height = height;
    }

    public Boolean getIsValid() {
        return isValid;
    }

    public void setIsValid(Boolean isValid) {
        this.isValid = isValid;
    }
}

ConfigurationProcessor - 处理配置对象和渲染 JSON 的类

package org.stackoverflow.helizone.test;

import java.lang.reflect.Field;

public class ConfigurationProcessor {
    public String toJson(Configuration configuration) {
        StringBuilder sb = new StringBuilder();

        sb.append("[");

        Field[] fields = configuration.getClass().getDeclaredFields();
        for (Field fld : fields) {
            String fieldName = fld.getName();

            JsonArrayMember fieldAnnotation = fld.getAnnotation(JsonArrayMember.class);
            if (fieldAnnotation == null) {
                // field not annotated with @JsonArrayMember, skip
                System.out.println("Skipping property " + fieldName + " -- no @JsonArrayMember annotation");
                continue;
            }

            if (!fld.getType().equals(Boolean.class)) {
                // field is not of boolean type -- skip??
                System.out.println("Skipping property " + fieldName + " -- not Boolean");
                continue;
            }

            Boolean value = null;

            try {
                value = (Boolean) fld.get(configuration);
            } catch (IllegalArgumentException | IllegalAccessException exception) {
                // TODO Auto-generated catch block
                exception.printStackTrace();
            }

            if (value == null) {
                // the field value is null -- skip??
                System.out.println("Skipping property " + fieldName + " -- value is null");
                continue;
            }

            if (value.booleanValue()) {
                if (sb.length() > 0) {
                    sb.append(", ");
                }

                sb.append(fieldAnnotation.value());
            } else {
                System.out.println("Skipping property " + fieldName + " -- value is FALSE");
            }
        }

        return sb.toString();
    }
}

Application.java - 示例测试应用程序

package org.stackoverflow.helizone.test;

public class Application {

    public static void main(String[] args) {

        Configuration configuration = new Configuration();
        configuration.setHeight(true);
        configuration.setWidth(true);
        configuration.setIsValid(false);

        ConfigurationProcessor cp = new ConfigurationProcessor();

        String result = cp.toJson(configuration);

        System.out.println(result);
    }
}

关于java - 如何从具有自定义值的类字段创建 Json 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48643617/

相关文章:

javascript - 对 JSON 数据的 Ajax 调用适用于 FF,但不适用于其他浏览器

java - 将 JSON 字段序列化为 JSON

Java - 如何知道线程何时等待?

java - 尝试使用 Apache Camel 将文件上传到 Amazon S3 时出现“AWS S3 Key header missing”错误

java - 尝试对空对象引用调用接口(interface)方法 'java.lang.Object[] java.util.Collection.toArray()'

c# - 如何将 json-patch 应用于 .net core 中的纯 json?

javascript - 在 JSPX 中转义 JSON

java - 然后我尝试使用 Jackson API 解析 json 输入流两次,并得到 java.io.EOFException

java - 尽管使用 JsonIgnore,但未能延迟初始化 ManyToMany 关系中的角色集合

java - throws 子句有什么意义?