Reputation: 2463
I have a class like
data class Data(
val field1: Int = 123
val field2: String = "Foo"
)
I have JSON like
{"field1": 123, "field2": "Foo"}
How can I check if my JSON really represents the structure of the class using Google GSON?
Upvotes: 0
Views: 1986
Reputation: 2044
Hi bro there are several Ways first by using code
import org.json.*;
public boolean isValidJSONTest(String yourjsonString) {
try {
new JSONObject(yourjsonString);
} catch (JSONException ex) {
try {
new JSONArray(yourjsonString);
} catch (JSONException ex1) {
return false;
}
}
return true;
}
For Gson code is like
Gson gson = new Gson();
try {
Object o = gson.fromJson(json, Object.class);
System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(o));
} catch (Exception e) {
System.out.println("invalid json format");
}
second you can use browser console and paste your string in console and enter
third they are several website that can validate json format or view etc https://jsonlint.com/
Upvotes: 1