简体   繁体   中英

Java Object to JSON using GSON

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"}

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"]]

Try using setPrettyPrinting with DisableHtml escaping.

Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
 JsonParser jp = new JsonParser();
 JsonElement je = jp.parse(jsonArray.toString());
 System.out.println( gson.toJson(je));

If you want to end up with a String, just do:

private String createArgsJsonArray(Object... argVals) {
    Gson gson = new Gson();
    return gson.toJson(argVals);
}

If you wish to collect it back and alter just do:

Object[] o = new Gson().fromJson(argValsStr, Object[].class);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM