2

I am new to java, and I am trying to create a json string with name and value.

public static String serializeToken(String name,String value){

    JsonObject json = new JsonObject();
    json.addProperty(name, value);

    return json.getAsString();
}

But the call to getAsString throws an exception and message is just:

JsonObject

Mubashar Abbas
  • 5,536
  • 4
  • 38
  • 49

1 Answers1

1

Here's the documentation of getAsString method and this is what it says:

convenience method to get this element as a string value.

Throws:

ClassCastException - if the element is of not a JsonPrimitive and is not a valid string value. IllegalStateException - if the element is of the type JsonArray but contains more than a single element.

So, if the element is not a Primitive (which it is not, in this case), it will throw an Exception. If you want to print json String then you need to call toString method, e.g.:

JsonObject json = new JsonObject();
json.addProperty("test", "value");
String jsonString = json.toString(); 
System.out.println(jsonString);
Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102