2016-12-05 11 views
1

:GSONを使用してGSONマップのキーと値のペア

{ 
    "status": "ok", 
    "questions": { 
    "1": "What was your childhood nickname?" 
    } 
} 

は、私は次のクラスにこれをシリアル化したい:

public class SecurityQuestionList { 
    public String status; 

    public Map<String, String> questions; 
} 

私はGsonオブジェクトにTypeAdapterを登録しましたが、質問は常に空です。

.registerTypeAdapter(new TypeToken<Map<String, String>>() {}.getType(), new TypeAdapter<Map<String, String>>() { 
        @Override 
        public void write(JsonWriter out, Map<String, String> value) throws IOException { 

        } 

        @Override 
        public Map<String, String> read(JsonReader in) throws IOException { 
         Map<String, String> map = new HashMap<String, String>(); 
         try { 
          in.beginArray(); 
          while (in.hasNext()) { 
           map.put(in.nextString(), in.nextString()); 
          } 
          in.endArray(); 
         } catch (IOException ex) { 

         } 

         return map; 
        } 
       }) 

私は間違っていますか?

答えて

1

Retrofitインスタンスを作成する場合は、addConverterFactory(GsonConverterFactory.create())を呼び出すだけで十分です。

1

「質問」は配列ではなくオブジェクトです。

"questions": { 
    "1": "What was your childhood nickname?" 
    } 

だから、あなたはちょうどここに私のテストコードです

in.beginArray(); 
while (in.hasNext()) { 
    map.put(in.nextString(), in.nextString()); 
} 
in.endArray(); 

in.beginObject(); 
while (in.hasNext()) { 
    map.put(in.nextName(), in.nextString()); 
} 
in.endObject(); 

に変更する必要があります。 1列29パス$ .questionsラインでBEGIN_ARRAYた期待BEGIN_OBJECTしかし:java.lang.IllegalStateException:によって引き起こさ :

@Test 
public void gson() { 
    String str = "{\n" + 
      " \"status\": \"ok\",\n" + 
      " \"questions\": {\n" + 
      " \"1\": \"What was your childhood nickname?\"\n" + 
      " }\n" + 
      "}"; 
    Gson gson = new GsonBuilder().registerTypeAdapter(new TypeToken<Map<String, String>>() { 
    }.getType(), new TypeAdapter<Map<String, String>>() { 
     @Override 
     public void write(JsonWriter out, Map<String, String> value) throws IOException { 
     } 
     @Override 
     public Map<String, String> read(JsonReader in) throws IOException { 
      Map<String, String> map = new HashMap<String, String>(); 
      try { 
       in.beginObject(); 
       while (in.hasNext()) { 
        map.put(in.nextName(), in.nextString()); 
       } 
       in.endObject(); 
      } catch (IOException ex) { 
      } 
      return map; 
     } 
    }).create(); 
    SecurityQuestionList securityQuestionList = gson.fromJson(str, SecurityQuestionList.class); 
    System.out.println(securityQuestionList.questions); 
} 

public static class SecurityQuestionList { 
    public String status; 
    public Map<String, String> questions; 
} 

そして印刷 {1=What was your childhood nickname?}

+0

私はあなたのコードを使用している場合は、エラーを取得しています – Ventis

+0

私のテストコードはOKです。あなたのjsonデータはその形式ですか? Json配列はこれのようなものです。 – ittianyu

+0

[{"" xxx ":" yyy "}、{" xxx ":" yyy "}] – ittianyu

関連する問題