Why primitive arrays are not allowed to add to a JSON structure in GSON

I want to do this to create a json object like below.

JsonObject      request             = new JsonObject();
request.addProperty("requestid", UUID.randomUUID().toString());
request.addProperty("type", "hotel");
request.addProperty("markups", new double[]{1.0,2.0,3.0}); // This says "The method addProperty(String, String) in the type JsonObject is not applicable for the arguments (String, double[])"
request.add("markups", new double[]{1.0,2.0,3.0});// This says "The method add(String, JsonElement) in the type JsonObject is not applicable for the arguments (String, double[])"

JSON object :

{
  "requestid": "05afcd81-9c59-4a21-a61e-ae48fda6bdd0",
  "type": "hotel",
  "markups": [1.0,2.0,3.0]
}

Please note that this is not about, fromJson and toJson thing. It is JSON CREATION and READING objects NOT a CONVERSION. So, how can I do it with the above implementation.

Answers


Since you want to use the parse tree object to build your JSON structure, you either need to instantiate and add the values to a JsonArray object, or use Gson and convert your double[]. I'm assuming you'd rather do the latter:

public static void main( String[] args ) 
{
    double[] d = new double[] { 1.0, 2.0};
    JsonElement e = new Gson().toJsonTree(d);
    JsonObject o = new JsonObject();
    o.add("array", e);
    System.out.println(o);
}

Output:

{"array":[1.0,2.0]}

The toJsonTree() method takes your Java array and converts it to the Gson parse tree JsonArray and returns it as the the superclass JsonElement


This can be done using JsonPrimitive as follows:

JsonObject      request             = new JsonObject();
request.addProperty("requestid", UUID.randomUUID().toString());
request.addProperty("type", "hotel");

JsonArray       jpArray         = new JsonArray();
jpArray.add(new JsonPrimitive(1.0));
jpArray.add(new JsonPrimitive(2.0));
jpArray.add(new JsonPrimitive(3.0));

request.add("markups", jpArray);

OutPut :

{
  "requestid": "6259f169-3a55-4a2e-b03c-5931d4daf2fd",
  "type": "hotel",
  "markups": [
    1.0,
    2.0,
    3.0
  ]
}

Need Your Help

Add LINQ Auto-Generated Value Marker [Column(IsDbGenerated=true)] in Buddy Class

c# linq linq-to-sql data-annotations buddy-class

is it possible to decorate a field of a LINQ generated class with [Column(IsDbGenerated=true)] using a buddy class (which is linked to the LINQ class via [MetadataType(typeof(BuddyMetadata))]) ?

VerifyError when instrumenting webapp on WildFly 8

java jboss wildfly instrumentation

I'm currently working on a project, trying to insert additional Log4j logging statements into a running webapp. To realise that, I start a Java agent via