The following code prints the following as input, but I would like to pass this JSON string as input directly to parse method (preferably as string argument). How should I do that?
{“val1″:”v1″,”val2″:”v2”}
import com.google.gson.*;
public class ParseJSON {
String val1;
String val2;
transient String val3;
public static void main(String[] args) {
Gson gson = new GsonBuilder().create();
ParseJSON parseJson = new ParseJSON();
parseJson.val1 = "v1";
parseJson.val2 = "v2";
parseJson.val3 = "v3";
String requestBody = gson.toJson(parseJson);
System.out.println(requestBody);
JsonParser parser = new JsonParser();
// JsonArray array = parser.parse(requestBody).getAsJsonArray();
}
}
The JSON that is being created would be considered a JSON object, not an array. To parse it correctly, you would need to call:
A JSON array would look more like this:
That’s a JSON array containing two JSON objects. JSON arrays have similar style to arrays you see in Java, they have
[]brackets and contain a comma separated list of objects/arrays/primitives.Additionally, you can parse it like this as well:
Once you have a
JsonElementyou can call methods likeisJsonArray()orisJsonObject()to find out what the top level JSON element is for theStringyou’ve parsed.