Parse Json to Java bean

Blanca Hdez picture Blanca Hdez · Aug 24, 2010 · Viewed 8.4k times · Source

I am trying to parse a Json file like this, generated by Exiftool:

[{
  "SourceFile": "videos/XaviHernandez.flv",
  "ExifTool": {
    "ExifToolVersion": 8.22
  },
  "System": {
    "FileName": "XaviHernandez.flv",
    "Directory": "videos",
    "FileSize": "16 MB",
    "FileModifyDate": "2010:06:17 09:57:21+02:00",
    "FilePermissions": "rw-r--r--"
  },
  "File": {
    "FileType": "FLV",
    "MIMEType": "video/x-flv"
  }
}]

In a Java bean with this structure:

public class MetadataContentBean {
    ExifToolBean exiftoolBean;
    String SourceFile;
    FileBean fileBean;
    SystemBean systemBean;
//Getters and setter
}

My java code is this:

    InputStream is = this.getClass().getClassLoader().getResourceAsStream(filename);
    String jsonTxt = IOUtils.toString(is);
    JSONArray json = (JSONArray) JSONSerializer.toJSON(jsonTxt);
    JSONObject metadatacontent = json.getJSONObject(0);
    ObjectMapper mapper = new ObjectMapper();
    MetadataContentBean meta = new MetadataContentBean();
    mapper.readValue(metadatacontent.toString(), MetadataContentBean.class);
    meta= (MetadataContentBean) JSONObject.toBean(metadatacontent, MetadataContentBean.class);

But I get this error:

net.sf.json.JSONException: java.lang.NoSuchMethodException: Unknown property 'ExifTool'
    at net.sf.json.util.PropertySetStrategy$DefaultPropertySetStrategy.setProperty(PropertySetStrategy.java:45)
    at net.sf.json.JSONObject.setProperty(JSONObject.java:1477)
    at net.sf.json.JSONObject.toBean(JSONObject.java:468)
    at net.sf.json.JSONObject.toBean(JSONObject.java:253)
    at com.playence.parser.JSon.Parser(JSon.java:66)
    at com.playence.parser.JSon.main(JSon.java:28)
Caused by: java.lang.NoSuchMethodException: Unknown property 'ExifTool'

I have checked in several forums, but the solution is this, so I don't know why I don't get results.

Any idea?

Answer

Blanca Hdez picture Blanca Hdez · Aug 24, 2010
ObjectMapper mapper = new ObjectMapper();
MetadataContentBean meta= mapper.readValue(metadatacontent.toString(), MetadataContentBean.class);

In this meta is all the information