i'm working with the youtube json from google-api-client :
{
"apiVersion": "2.0",
"data": {
"updated": "2011-01-05T13:48:33.146Z",
"totalItems": 4,
"startIndex": 1,
"itemsPerPage": 1,
"items": [
{
"id": "YfUzMkAlOBI",
"uploaded": "2010-12-29T16:50:47.000Z",
"updated": "2010-12-29T16:50:47.000Z",
"uploader": "devandroidcs",
"category": "Entertainment",
"title": "Teste 2",
"description": "Description do teste2",
"tags": [
"mobile"
],
开发者_开发百科 "thumbnail": {
"sqDefault": "http://i.ytimg.com/vi/YfUzMkAlOBI/default.jpg",
"hqDefault": "http://i.ytimg.com/vi/YfUzMkAlOBI/hqdefault.jpg"
},
"player": {
"default": "http://www.youtube.com/watch?v\u003dYfUzMkAlOBI&feature\u003dyoutube_gdata_player",
"mobile": "http://m.youtube.com/details?v\u003dYfUzMkAlOBI"
}
.
.
.
}
at this point i should create a field name called default at my parse java class. Already done this parse work with the other fields , the problem is that , default is a private java name so i can't call a variable default .
how can i manage that ?
I believe your answer lies in the JSON Field Naming Support:
Gson supports some pre-defined field naming policies to convert the standard Java field names (i.e. camel cased names starting with lower case --- "sampleFieldNameInJava") to a Json field name (i.e. sample_field_name_in_java or SampleFieldNameInJava).
See for instance the following example:
private class SomeObject {
@SerializedName("custom_naming") private final String someField;
private final String someOtherField;
public SomeObject(String a, String b) {
this.someField = a;
this.someOtherField = b;
}
}
So you should be able to define the field mapping to the default value like this:
@SerializedName("default")
private final String someOtherNameThanDefault;
If you're using the @Key annotation for your mapped fields, you just need to make use of a custom value that can be passed to this annotation. So choose a legal name for your field and map it as @Key("default"):
@Key("default")
private String defaultUrl;
Just say it from my personal experience, @Key may not work on serialization/de-serialization when choosing the wrong Json parser.
(1) When you use Gson parser, like below :
GsonBuilder gsb = new GsonBuilder();
Gson gson = gsb.create();
OneDriveItem oneDriveItem = gson.fromJson(jasonData1, OneDriveItem.class);
@Key does not work, you should use @SerializedName to annotate the field name.
(2) When you use JsonFactory from the package com.google.api.client.json, like below :
JacksonFactory jsonFactory=new JacksonFactory();
@Key should work.
精彩评论