簡體   English   中英

從 JSON 獲取數據

[英]Getting data from JSON

我試圖從這個 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 中。

感謝您的任何幫助和/或建議!

謝謝你的幫助!

希望這可以幫助:

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

    }
}

調試.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;
    }

}

結果.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;
    }

}

建議。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;
    }

}

我建議您使用 flexjson 庫http://flexjson.sourceforge.net/恕我直言,它更簡單且可用的庫。 我第一次使用了 GSON,但后來我所有的項目都切換到了 flexjson 而不是 GSON。

使用 android 中的標准 json 類

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;
}

理想情況下,我想把它全部放在 HashMap 中。

如果可以切換庫, Jackson只需一行代碼即可實現。

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

這會將任何 JSON object 反序列化為HashMap ,僅由 ZD52387880E371EA22138177A 組件組成。 我還沒有看到另一個可以做到這一點的 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的博客文章中復制了這段代碼。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM