2013-05-16 154 views
1

我有以下由REST API调用返回的JSON。是否有可能将此构造读入Java对象?这里是JSON数据:将JSON数组解析为Java对象

[ 
    { 
     "dirName": "/", 
     "files": [ 
      { 
       "fileName": "Dog prototype", 
       "fileId": "0a8cc3ed206", 
       "revision": { 
        "revisedBy": "Billy Jean", 
        "imageId": "80e94300a7286" 
       }, 
       "creatorName": "Billy Jean", 
       "disciplineName": "Structural Engineering", 
       "projectName": "Army Dog Reengineering Project", 
       "directoryId": "ed8202c43332" 
      }, 
      { 
       "fileName": "Office space plan", 
       "fileId": "e5c4ceb41e9b", 
       "revision": { 
        "revisedBy": "Winslow Homer", 
        "imageId": "" 
       }, 
       "creatorName": "Winslow Homer", 
       "disciplineName": "Interior Planning", 
       "projectName": "Friggle LLC Office Redesign", 
       "directoryId": "ed85a61202c43332" 
      } 
     ], 
     "dirId": "ed85a66f08cd49332" 
    } 
] 

Gson能用这样的东西吗?

感谢

回答

6

您需要模仿的数据结构,然后GSON库会照顾的,只要确保它们匹配。

class Directory { 
    String dirName; 
    File[] files; 
    String dirId; 
} 

class File { 
    String fileName; 
    String fileId; 
    Revision revision; 
    String creatorName; 
    String disciplineName; 
    String projectName; 
    String directoryId 
} 

class Revision { 
    String revisedBy; 
    String imageId; 
} 

Directory[] directories = gson.fromJson(data, Directory[].class); 
+0

这就像一个魅力工作。谢谢! – user2371790