Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create json object with key and value, where value is array

I need to make json object with key, and value, where value is array of values. How could i do that ?

{"propName" : "favouriteObjectsIds", 
 "value": [
        "5c93f4cc3a6565000483248d",
        "5c93f7843a6565000483248e"
        ] 
}

I have tried like this

public void add(String propertyName, String[] values){
        JsonArray array1 = new JsonArray();
        for(int i = 0; i < values.length; i++){
            array.add(values[i]);
        }

        JsonObject json = new JsonObject();
        json.addProperty("propName", propertyName);
        json.addProperty("value" ,array.toString());
    }

but array.toString() gives me such output

{"propName":"favouriteObjectsIds",
"value":"[\"5c93f4cc3a6565000483248d\",\"5c9b82ad24b33b0004227322\"]"}
like image 393
Gabrielius Pileckis Avatar asked Oct 19 '25 14:10

Gabrielius Pileckis


1 Answers

You should use .add instead of .addProperty for JsonElements

public void add(String propertyName, String[] values){

    JsonArray array = new JsonArray();
    for(int i = 0; i < values.length; i++){
        array.add(values[i]);
    }

    JsonObject json = new JsonObject();
    json.addProperty("propName", propertyName);
    json.add("value" ,array);
}
like image 171
Beyazid Avatar answered Oct 21 '25 02:10

Beyazid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!