3

OK, so I'm using Jackson to parse a JSON file, problem is, the file is one big unnamed array. It is in the format:

[ {json stuff}, {json stuff}, ..., {json stuff} ]

All the json stuff is just regular JSON expressions that I will have to deal with once I actually get this into an array.

I can't find any real tutorials about how to map things using Jackson, but need to find a way to map each of these different things into an array, and then parse each specific thing using Jackson into it's individual components. Any idea how to do this?

P.S. The only real tutorial I could find was this: http://www.studytrails.com/java/json/java-jackson-Data-Binding.jsp

Where DataSet[] is an array that is named in the file. I want to figure out how to do what that tutorial does, except with the example above, where the array does not start off with a name.

P.P.S. Here is the code I'm using:

Basic Jackson code to map into my item:

ObjectMapper mapper = new ObjectMapper();
    mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

    URL url = null;
    try {
        url = new URL("my JSON URL");
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

    try {
        ContactInfo contacts = mapper.readValue(url, ContactInfo.class);
    } catch (JsonParseException e) {
        e.printStackTrace();
    } catch (JsonMappingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

Then my ContactInfo class is just the Getters and Setters with the defined fields in the JSON URL. The problem is, without a name to the Array that breaks up all the different JSON nodes, I don't know how to access individual contact values, or if they are being overwritten.

Bill L
  • 2,576
  • 4
  • 28
  • 55

1 Answers1

5

Just use a ContactInfo[] as the class type. Here's a working example.

public class Example {
    public static void main(String[] args) throws Exception {
        String json = "[{\"name\":\"random\"},{\"name\":\"random\"},{\"name\":\"random\"}]";
        ObjectMapper mapper = new ObjectMapper();
        ContactInfo[] contactInfos = mapper.readValue(json, ContactInfo[].class);
        System.out.println(contactInfos.length);
    }

    static class ContactInfo {
        private String name;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    } 
}

Alternatively, you can use a List<ContactInfo>, but you'll need a TypeReference.

List<ContactInfo> contactInfos = mapper.readValue(json, new TypeReference<List<ContactInfo>>() {});
System.out.println(contactInfos.size());
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • That got it, still learning Jackson, just started today and there is a severe lack of tutorials out there. Thanks for the help! – Bill L Mar 06 '14 at 18:55