How can I check that the JSONObject object does not contain any embedded JSON objects?

That is, an object of the form

{ "first" : "1", "second" : "2" } 

must be valid and the view object

 { "first" : "1", "inner" : { "inner-field" : "data" } } 

must be invalid.

My attempt to follow one of the tips:

 package json; import com.google.gson.JsonObject; import org.junit.Test; import com.google.gson.JsonParser; import com.google.gson.JsonElement; public class TestNested { @Test public void testHasNestedJSON() { final String nested = "{ \"data\" : \"test\", \"inner\" : { \"key\" : \"inn\"} }"; System.out.println(nested); JsonParser parser = new JsonParser(); System.out.println(parser.parse(nested).getClass()); } @Test public void testPlainJSON() { final String plain = "{ \"data\" : \"test\" }"; System.out.println(plain); JsonParser parser = new JsonParser(); JsonElement jsonElement = parser.parse(plain); JsonObject jsonObject = jsonElement.getAsJsonObject(); System.out.println(jsonElement.getClass()); } } 

    1 answer 1

    You need to parse JSON (for example, using JsonParser ), then see the type of the returned object. How to parse json can be found here .

     new JsonParser().parse(json); 
    • How to see the type and what information to look for to determine the nesting? - typemoon
    • The type can be viewed using getClass() . To determine nesting, the returned type should not be primitive, i.e. You can watch if the type is JsonObject , then you have nesting. - Roman C
    • I always have the JsonObject type: the same for JSON with and without nesting - typemoon
    • then you are doing something wrong - Roman C
    • can you see what exactly i am doing wrong? Code added to your post. - typemoon