Java Object to JSON using GSON

user2761431 :

I have an Object array which is a list of argument values a function could take. This could be any complex object.

I am trying to build a json out of the Object array using gson as below:

private JsonArray createArgsJsonArray(Object... argVals) {
    JsonArray argsArray = new JsonArray();
    Arrays.stream(argVals).forEach(arg -> argsArray.add(gson.toJson(arg)));
    return argsArray;
}
  1. This treats all the arg values as String.
  2. It escapes the String args

    "args":["\"STRING\"","1251996697","85"]
    

I prefer the following output:

   "args":["STRING",1251996697,85]

Is there a way to achieve this using gson?

I used org.json, I was able to achieve the desired result, but it does not work for complex objects.

EDIT:

I applied the solution provided by @Michał Ziober, but now how do I get back the object.

Gson gson = new Gson();
Object strObj = "'";
JsonObject fnObj = new JsonObject();
JsonObject fnObj2 = new JsonObject();
fnObj.add("response", gson.toJsonTree(strObj));
fnObj2.addProperty("response", gson.toJson(strObj));

System.out.println(gson.fromJson(fnObj.toString(), 
Object.class)); --> prints {response='}   //Not what I want!
System.out.println(gson.fromJson(fnObj2.toString(), 
Object.class)); --> prints {response="\u0027"}
Michał Ziober :

Use toJsonTree method:

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import java.util.Date;

public class GsonApp {

  public static void main(String[] args) {
    GsonApp app = new GsonApp();
    System.out.println(app.createArgsJsonArray("text", 1, 12.2D));
    System.out.println(app.createArgsJsonArray(new Date(), new A(), new String[] {"A", "B"}));
  }

  private Gson gson = new GsonBuilder().create();

  private JsonArray createArgsJsonArray(Object... argVals) {
    JsonArray argsArray = new JsonArray();

    for (Object arg : argVals) {
      argsArray.add(gson.toJsonTree(arg));
    }

    return argsArray;
  }
}

class A {
  private int id = 12;
}

Above code prints:

["text",1,12.2]
["Sep 19, 2019 3:25:20 PM",{"id":12},["A","B"]]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=311040&siteId=1