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

hellzone

I want to generate a JSON array(configuration) with respect to Configuration class fields. What I want to do is If some field is true, then add its custom predefined value to JSON array.

How can I create a JSON array with these values?

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

    //Getters and setters
}

for example if all fields are true I want to generate a JSON array like;

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

if only isValid and height are true;

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

What did I do so far;

String configuration = "["; 

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

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

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

....//After 40 fields

configuration += "]";
Vasil Svetoslavov

In such cases I find it useful to write an annotation and use reflection. Below is a simple example of this. You can also combine this with the JsonArray suggested by VPK.

JsonArrayMember.java -- the annotation we use

package org.stackoverflow.helizone.test;

import java.lang.annotation.*;

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

Configuration.java -- the Configuration class with its fields annotated with @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 - the class to handle processing the configuration object and rendering the 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 - a sample test application

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Extract certain values from XML response to create custom JSON array

How to get custom fields values from WooCommerce orders

How to create a Dataset from custom class Person?

How to create JSON from strings without creating a custom class using JSON.Net library

How to create a DataFrame from custom values

How to create a list of values from a dictionary array?

How to create json object dynamically from UI using values from input fields before sending to API

Extract values from fields in an array of JSON objects

How to create dict from class without None fields?

How to create instances from Array values

How to create an array with null values after first item with custom value?

How to create custom json from pandas dataframe

How to create a multidimensional array with values from dynamically created form fields, using jquery?

Rails 4- How to create checkboxes in form where values come from a class variable thats an array

How to create custom class from variable? (not Object)

How to create a NSDictionnary from an array with custom cells

How to create JSON from a custom formatted string

Create array from values of data fields in DOM elements

How to create Json from header and detail class

create custom objects array from json data

Create custom JSON from array of objects

JOLT transform JSON merge array, but values from another fields

How to Create an Array From JSON and Import the Values to Multiple Rows in a Google Sheet Using Google Apps Scripts

How to create array of JSON objects with multiple values?

C# | Create a json string out of static class fields with values

How create a new array from the fields of the objects object and the array

KQL: How to create new fields of keys and values from a field with JSON object?

How to create array using values from input array and another fields from hierarchy using JOLT

Create flattened array from array of JSON values Athena