Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.dhenton9000.json; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.List; import org.apache.commons.io.FileUtils; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.type.TypeFactory; /** * http://wiki.fasterxml.com/JacksonInFiveMinutes * @author dhenton */ public class JacksonFromStringDemo { private static Logger LOG = LogManager.getLogger(JacksonFromStringDemo.class); public void demoReadFromString() throws IOException { String test = "{\"id\":44444,\"name\":\"Bonzo\",\"version\":1,\"zipCode\":\"55555\",\"city\":null,\"state\":null,\"reviews\":[]}"; ObjectMapper mapper = new ObjectMapper(); Restaurant res = mapper.readValue(test, Restaurant.class); LOG.debug("restaurant " + res); File f = convertClassPathToFileRef("/restaurants.json"); // LOG.debug( FileUtils.readFileToString(f, "UTF-8")); List<Restaurant> restaurants = mapper.readValue(f, TypeFactory.collectionType(List.class, Restaurant.class)); for (Restaurant r : restaurants) { LOG.debug(r.toString()); } } public File convertClassPathToFileRef(String path) throws FileNotFoundException { if (this.getClass().getResource(path) != null) return new File(FileUtils.toFile(getClass().getResource(path)).getAbsolutePath()); else { String info = String.format("unable to find file at '%s'", path); throw new FileNotFoundException(info); } } public static void main(String[] args) { JacksonFromStringDemo j = new JacksonFromStringDemo(); try { j.demoReadFromString(); } catch (IOException ex) { LOG.error("main " + ex.getMessage()); } } }