4

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\"]"}
0

3 Answers 3

5

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);
}
Sign up to request clarification or add additional context in comments.

Comments

0

you can build you json with ArrayList like this :

public void add(String propertyName,ArrayList<String> list){

        Map map = new LinkedHashMap();
        map.put("propName", propertyName);
        map.put("value", list);


         JSONObject jObject = new JSONObject(map);
     //  convert JSONObject to JSON to String
         String  json = jObject.toString();

}

Comments

0

All the examples above create two properties, each with a key(name) and a value. The first property key is "propName" which has the value of "favouriteObjectsIds", the second property key is "value" which has the value of "["5c93f4cc3a6565000483248d","5c93f7843a6565000483248e"]"

I suspect that you would rather have this:

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

If that is true, you could do so in this way:

String myJson = "{\"favouriteObjectsIds\":[\"5c93f4cc3a6565000483248d\",\"5c93f7843a6565000483248e\"]}"; 

JSONObject jObject = new JSONObject(myJson );

JSONArray jArray = jObject.getJSONArray("favouriteObjectsIds");

1 Comment

no, that's not the case. I need such json format, becouse my rest api takes such one for patch method, but thanks for response .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.