2013-01-16 97 views
0

我一直在嘗試使用gson從json字符串生成協議緩衝區消息。有沒有人知道如果可以做到這一點?如何使用Gson從json構建協議緩衝區消息?

我已經嘗試:

Gson gson = new Gson(); 
Type type = new TypeToken<List<PROTOBUFFMESSAGE.Builder>>() {}.getType(); 
List<PROTOBUFFMESSAGE.Builder> list = (List<PROTOBUFFMESSAGE.Builder>) gson.fromJson(aJsonString, type); 

Gson gson = new Gson(); 
Type type = new TypeToken<List<PROTOBUFFMESSAGE>>() {}.getType(); 
List<PROTOBUFFMESSAGE> list = (List<PROTOBUFFMESSAGE>) gson.fromJson(aJsonString, type); 

的JSON內的消息使用相同的名稱在協議緩衝器即:

message PROTOBUFFMESSAGE { 
    optional string this_is_a_message = 1; 
    repeated string this_is_a_list = 2; 
} 

會導致JSON:

[ 
    { 
     "this_is_a_message": "abc", 
     "this_is_a_list": [ 
      "123", 
      "qwe" 
     ] 
    }, 
    { 
     "this_is_a_message": "aaaa", 
     "this_is_a_list": [ 
      "foo", 
      "bar" 
     ] 
    } 
] 

雖然獲取生成正確數量PROTOBUFFMESSAGE的列表,它們包含所有的字段設置爲null,所以我不知道這是否與映射出了問題,反射系統沒有檢測到protobuffs字段或其他東西。如果有人知道如何做到這一點,那就太好了。順便說一句我在這裏談論Java。

編輯:

改變了JSON的名字:

 { 
      "thisIsAMessage_": "abc", 
      "thisIsAList_": [ 
       "123", 
       "qwe" 
      ] 
     } 

讓德序列發生。而且它除了拋出名單的工作:

java.lang.IllegalArgumentException: Can not set com.google.protobuf.LazyStringList field Helper$...etc big path here...$PROTOBUFFMESSAGE$Builder.thisIsAList_ to java.util.ArrayList 
+1

如果用的protobuf然後'可選的字符串this_is_a_message = 1生成的消息開放代碼;'將成爲'私人字符串this_is_a_message_;'筆記最後下劃線和setters/getters。 –

+0

@NikolayKuznetsov這樣做的工作,但與語法'thisIsAMessage_'。現在的問題是,列表'thisIsAList_'是由一個'UnmodifiableLazyStringList'生成的,它在反序列化時拋出一個異常:\ – fmsf

+0

什麼異常?反序列化意味着在接收端? –

回答

0

聽起來像是你將不得不使用GsonBuilder建立一個Gson對象,編寫並註冊一個類型的適配器給它com.google.protobuf.LazyStringList對象。

0

相反發起Gson對象通過構造函數中使用這個片段的:

GsonBuilder builder = new GsonBuilder(); 
builder.registerTypeAdapter(LazyStringList.class, new TypeAdapter<LazyStringList>() { 

    @Override 
    public void write(JsonWriter jsonWriter, LazyStringList strings) throws IOException { 

    } 

    @Override 
    public LazyStringList read(JsonReader in) throws IOException { 
    LazyStringList lazyStringList = new LazyStringArrayList(); 

    in.beginArray(); 

    while (in.hasNext()) { 
     lazyStringList.add(in.nextString()); 
    } 

    in.endArray(); 

    return lazyStringList; 
    } 
});