2016-02-18 109 views
0

我有JSON:映射JSON数组使用对象的字符串名称(JAVA)

{ 
    "albums": [ 
    { 
     "default": { 
     "privacy": "public" 
      ...... 
     } 
     } 
    }, 
    { 
     "second_album": { 
     "privacy": "public" 
     ...... 
     } 
    }, 
    { 
     "third_album": { 
     "privacy": "public" 
     ...... 
     } 
    } 
    } 
    ] 
} 

我想使Java对象为这个JSON。

public class AlbumsResponse { 

    private List<Album> albums = new ArrayList<>(); 

    public List<Album> getAlbums() { 
     return albums; 
    } 

    public void setAlbums(List<Album> albums) { 
     this.albums = albums; 
    } 
} 

public class Album { 

    private Title title; 

    public Title getTitle() { 
     return title; 
    } 

    public void setTitle(Title title) { 
     this.title = title; 
    } 

} 

但你可以看到专辑有没有任何“标题”字段中JSON,但有这样的事情

"second_album": { 
    "privacy": "public" 
    ...... 
    } 

如何使用这方面的工作?如何将json-object的名称作为json-array中的单位转换为java-object中的字段“title”?

+0

可以使用杰克逊库https://github.com/FasterXML/jackson-databind –

+0

我不明白,我究竟是如何能做到这一点。我需要用Gson来做。 –

回答

0

根据你的问题,我不完全确定你想如何将显示的对象转换为Title,但我相信你可以通过custom deserializer实现你正在寻找的东西。

例如,下面的解串器采用JSON对象的第一个关键,包装这在Title,然后返回一个AlbumTitle

public static class AlbumDeserializer implements JsonDeserializer<Album> { 
    @Override 
    public Album deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { 
     // Get the key of the first entry of the JSON object 
     JsonObject jsonObject = json.getAsJsonObject(); 
     Map.Entry<String, JsonElement> firstEntry = jsonObject.entrySet().iterator().next(); 
     String firstEntryKey = firstEntry.getKey(); 

     // Create a Title instance using this key as the title 
     Title title = new Title(); 
     title.setTitle(firstEntryKey); 

     // Create an Album instance using this Title 
     Album album = new Album(); 
     album.setTitle(title); 
     return album; 
    } 
} 

然后,您可以用注册这个自定义解串器您Gson实例,将您JSON与它:

Gson gson = new GsonBuilder() 
     .registerTypeAdapter(Album.class, new AlbumDeserializer()) 
     .create(); 

AlbumsResponse response = gson.fromJson(json, AlbumsResponse.class); 

System.out.println(response); 

假设你的类的基本原则,实施toString,运行这个机智^ h的例子打印如下:

AlbumsResponse{albums=[Album{title=Title{title='default'}}, Album{title=Title{title='second_album'}}, Album{title=Title{title='third_album'}}]} 
相关问题