JSON - check if array exists

I have a JSON file filled with some arrays. I was wondering if anyone knows how I can check if there is an array of specifications in the file.

EDIT: this is how my file is organized.

{ 'Objects': { 'array1': [ { 'element1': 'value', 'element1': 'value', 'element1': 'value' } ], // more arrays. } 

I want to search through arrays and check if an array of specifications exists. If this happens, I will serialize it. }

Thank you in advance for your help.

+4
source share
3 answers

Below is an example of an approach that you can use with Jackson. It uses the same JSON structure as in the latest issue updates, as well as the corresponding Java data structure. This makes it very easy to deserialize with just one line of code.

I decided to just deserialize the JSON array into a Java list. This is very easy to change to use a Java array instead.

(Note that there are problems with this JSON structure that I suggest changing if it is in your control to change it.)

input.json:

 { "objects": { "array1": [ { "element1": "value1", "element2": "value2", "element3": "value3" } ], "array2": [ { "element1": "value1", "element2": "value2", "element3": "value3" } ], "array3": [ { "element1": "value1", "element2": "value2", "element3": "value3" } ] } } 

Java Code:

 import java.io.File; import java.util.List; import java.util.Map; import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility; import org.codehaus.jackson.map.ObjectMapper; public class Foo { public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper(); // configure Jackson to access non-public fields mapper.setVisibilityChecker(mapper.getVisibilityChecker().withFieldVisibility(Visibility.ANY)); // deserialize JSON to instance of Thing Thing thing = mapper.readValue(new File("input.json"), Thing.class); // look for the target named array2 if (thing.objects.containsKey("array2")) { // an element with the target name is present, make sure it a list/array if (thing.objects.get("array2") instanceof List) { // found it List<OtherThing> target = thing.objects.get("array2"); OtherThing otherThing = target.get(0); System.out.println(otherThing.element1); // value1 System.out.println(otherThing.element2); // value2 System.out.println(otherThing.element3); // value3 } // else do something } // else do something } } class Thing { Map<String, List<OtherThing>> objects; } class OtherThing { String element1; String element2; String element3; } 
+4
source

So you want to upload a file with some JSON arrays and look for these arrays for something? I would recommend using a good JSON parser such as Jackson .

+1
source

You can use "value instanceof Array"

-1
source

All Articles