簡體   English   中英

如何從具有自定義值的類字段創建 Json 數組?

[英]How to create a Json Array from class fields with custom values?

我想針對 Configuration 類字段生成一個 JSON 數組(配置)。 我想要做的是如果某個字段為真,則將其自定義預定義值添加到 JSON 數組中。

如何使用這些值創建 JSON 數組?

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

    //Getters and setters
}

例如,如果所有字段都為真,我想生成一個 JSON 數組,例如;

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

如果只有 isValid 和 height 為真;

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);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM