JSON - Check if an array exists
I have a JSON file filled with some arrays. I was wondering if anyone knows how i can check if a specifik array exists 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 the arrays and check if a spec开发者_StackOverflow社区ifik array exists or not. If it doese then I will serialize it. }
Thanks in advance for all help
Following is an example of an approach you could take using Jackson. It uses the same JSON structure presented in the latest question updates, along with a matching Java data structure. This allows for very easy deserialization, with just one line of code.
I chose to just deserialize the JSON array to a Java List. It's very easy to change this to use a Java array instead.
(Note that there are issues with this JSON structure that I suggest changing, if it's 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's 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;
}
So you want to load a file with some JSON arrays and search those arrays for something? I would recommend using a good JSON parser like Jackson.
You can use "value instanceof Array"
精彩评论