Получение данных из JSON - PullRequest
1 голос
/ 06 июля 2011

Я пытаюсь получить значения из этой строки JSON, но мне трудно это сделать.

{"DebugLogId":"1750550","RequestId":"17505503","Result":
{"Code":"","DebugLogId":"1750550","Message":""},
    "Suggestions":[
        {"Ranking":"1","Score":"60","Title":"This is a test message 1"},
        {"Ranking":"2","Score":"60","Title":"This is a test message 2"}         
    ]}

Каким способом было бы проще всего получить доступ к данным в «Предложениях»? Я использую модуль GSON. В идеале я хотел бы поместить все это в HashMap.

Спасибо за любую помощь и / или предложения!

Спасибо за любую помощь!

Ответы [ 4 ]

5 голосов
/ 06 июля 2011

Надеюсь, это поможет:

App.java:

package sg.java.play_sof_json_6596072;

import com.google.gson.Gson;

public class App {
    public static void main(String[] args) {
        Gson gson = new Gson();
        String jsonString = "{\"DebugLogId\":\"1750550\",\"RequestId\":\"17505503\",\"Result\":{\"Code\":\"\",\"DebugLogId\":\"1750550\",\"Message\":\"\"},\"Suggestions\":[{\"Ranking\":\"1\",\"Score\":\"60\",\"Title\":\"This is a test message 1\"},{\"Ranking\":\"2\",\"Score\":\"60\",\"Title\":\"This is a test message 2\"}]}";

        Debug obj = (Debug) gson.fromJson(jsonString, Debug.class);

        System.out.println(obj.getSuggestionList().get(1).getTitle());

    }
}

Debug.java:

package sg.java.play_sof_json_6596072;

import java.util.List;

import com.google.gson.annotations.SerializedName;

public class Debug {
    @SerializedName("DebugLogId")
    private String debugLogId;
    @SerializedName("RequestId")
    private String requestId;
    @SerializedName("Result")
    private Result result;
    @SerializedName("Suggestions")
    private List<Suggestion> suggestionList;

    /**
     * @return the debugLogId
     */
    public final String getDebugLogId() {
        return this.debugLogId;
    }

    /**
     * @param debugLogId the debugLogId to set
     */
    public final void setDebugLogId(String debugLogId) {
        this.debugLogId = debugLogId;
    }

    /**
     * @return the requestId
     */
    public final String getRequestId() {
        return this.requestId;
    }

    /**
     * @param requestId the requestId to set
     */
    public final void setRequestId(String requestId) {
        this.requestId = requestId;
    }

    /**
     * @return the result
     */
    public final Result getResult() {
        return this.result;
    }

    /**
     * @param result the result to set
     */
    public final void setResult(Result result) {
        this.result = result;
    }

    /**
     * @return the suggestionList
     */
    public final List<Suggestion> getSuggestionList() {
        return this.suggestionList;
    }

    /**
     * @param suggestionList the suggestionList to set
     */
    public final void setSuggestionList(List<Suggestion> suggestionList) {
        this.suggestionList = suggestionList;
    }

}

Result.java:

package sg.java.play_sof_json_6596072;

import com.google.gson.annotations.SerializedName;

public class Result {
    @SerializedName("Code")
    private String code;
    @SerializedName("DebugLogId")
    private String debugLogId;
    @SerializedName("Message")
    private String messahe;

    /**
     * @return the code
     */
    public final String getCode() {
        return this.code;
    }

    /**
     * @param code the code to set
     */
    public final void setCode(String code) {
        this.code = code;
    }

    /**
     * @return the debugLogId
     */
    public final String getDebugLogId() {
        return this.debugLogId;
    }

    /**
     * @param debugLogId the debugLogId to set
     */
    public final void setDebugLogId(String debugLogId) {
        this.debugLogId = debugLogId;
    }

    /**
     * @return the messahe
     */
    public final String getMessahe() {
        return this.messahe;
    }

    /**
     * @param messahe the messahe to set
     */
    public final void setMessahe(String messahe) {
        this.messahe = messahe;
    }

}

Suggestion.java:

package sg.java.play_sof_json_6596072;

import com.google.gson.annotations.SerializedName;

public class Suggestion {
    @SerializedName("Ranking")
    private String ranking;
    @SerializedName("Score")
    private String score;
    @SerializedName("Title")
    private String title;

    /**
     * @return the ranking
     */
    public final String getRanking() {
        return this.ranking;
    }

    /**
     * @param ranking the ranking to set
     */
    public final void setRanking(String ranking) {
        this.ranking = ranking;
    }

    /**
     * @return the score
     */
    public final String getScore() {
        return this.score;
    }

    /**
     * @param score the score to set
     */
    public final void setScore(String score) {
        this.score = score;
    }

    /**
     * @return the title
     */
    public final String getTitle() {
        return this.title;
    }

    /**
     * @param title the title to set
     */
    public final void setTitle(String title) {
        this.title = title;
    }

}
1 голос
/ 06 июля 2011

Я рекомендую использовать библиотеку flexjson http://flexjson.sourceforge.net/ ИМХО, это более простая и удобная библиотека. Я впервые использовал GSON, но затем переключил все свои проекты на flexjson вместо GSON.

0 голосов
/ 06 июля 2011

В идеале я хотел бы поместить все это в HashMap.

Если вы можете переключать библиотеки, Джексон может добиться этого всего одной строкой кода.

Map map = new ObjectMapper().readValue(json, Map.class);

Это десериализовало бы любой объект JSON в HashMap, состоящий только из компонентов Java SE.Я еще не видел другой библиотеки Java-to / from-JSON, которая могла бы сделать это.

То же самое можно сделать с помощью Gson, но для этого требуется еще несколько строк кода.Вот одно из таких решений.

JsonElement je = new JsonParser().parse(json);  
JsonObject jo = je.getAsJsonObject();
Map<String, Object> map = createMapFromJsonObject(jo);

// ...

static Map<String, Object> createMapFromJsonObject(  
    JsonObject jo)  
{  
  Map<String, Object> map = new HashMap<String, Object>();  
  for (Entry<String, JsonElement> entry : jo.entrySet())  
  {  
    String key = entry.getKey();  
    JsonElement value = entry.getValue();  
    map.put(key, getValueFromJsonElement(value));  
  }  
  return map;  
}  

static Object getValueFromJsonElement(JsonElement je)  
{  
  if (je.isJsonObject())  
  {  
    return createMapFromJsonObject(je.getAsJsonObject());  
  }  
  else if (je.isJsonArray())  
  {  
    JsonArray array = je.getAsJsonArray();  
    List<Object> list = new ArrayList<Object>(array.size());  
    for (JsonElement element : array)  
    {  
      list.add(getValueFromJsonElement(element));  
    }  
    return list;  
  }  
  else if (je.isJsonNull())  
  {  
    return null;  
  }  
  else // must be primitive  
  {  
    JsonPrimitive p = je.getAsJsonPrimitive();  
    if (p.isBoolean()) return p.getAsBoolean();  
    if (p.isString()) return p.getAsString();  
    // else p is number, but don't know what kind  
    String s = p.getAsString();  
    try  
    {  
      return new BigInteger(s);  
    }  
    catch (NumberFormatException e)  
    {  
      // must be a decimal  
      return new BigDecimal(s);  
    }  
  }  
}

(я скопировал этот код из своего поста в блоге на http://programmerbruce.blogspot.com/2011/06/gson-v-jackson.html.)

0 голосов
/ 06 июля 2011

Использование стандартных классов JSON в Android:

JSONObject o = new JSONObject("your string");
JSONArray a = o.getJSONArray("Suggestions");
int i = 0;
while ( i < a.length())
{
    o = a.getJSONObject(i);
    //do something with o, like o.getString("Title") ...
    ++i;
}
...