2016-12-05 4 views
1

с помощью дооснащения 2 Я потребляющих API, который дает возвращает объект JSON с помощью следующей реакции:GSON карта ключевых пар значений

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

Использование GSON, я хотел сериализация это к следующему классу:

public class SecurityQuestionList { 
    public String status; 

    public Map<String, String> questions; 
} 

Я зарегистрировал TypeAdapter с моим объектом Gson, но вопросы всегда пусты.

.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

Достаточно позвонить addConverterFactory(GsonConverterFactory.create()) при создании экземпляра Retrofit.

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(); 

Вот мой тестовый код.

@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

Я получаю сообщение об ошибке, если я использую ваш код: Вызванный: java.lang.IllegalStateException: Ожидаемый BEGIN_OBJECT но BEGIN_ARRAY в строке 1 колонки 29 пути $ .questions – Ventis

+0

Мой тестовый код в порядке. Ваши данные json похожи на этот формат? Json-массив подобен этому. – ittianyu

+0

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

Смежные вопросы