【问题标题】:Getting data from JSON从 JSON 获取数据
【发布时间】:2011-09-29 13:52:55
【问题描述】:

我正在尝试从这个 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 中。

感谢您的帮助和/或建议!

感谢您的帮助!

【问题讨论】:

  • 我今天早些时候回答的一些问题可能会对您有所帮助。 See here

标签: java json map hashmap gson


【解决方案1】:

理想情况下,我想把它全部放在一个 HashMap 中。

如果您可以切换库,Jackson 只需一行代码即可实现。

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

这会将任何 JSON 对象反序列化为仅由 Java SE 组件组成的 HashMap。我还没有看到另一个可以做到这一点的 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 的博客文章中复制了这段代码。)

【讨论】:

    【解决方案2】:

    希望这会有所帮助:

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

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

    【讨论】:

    • 谢谢你!这非常完美!注释“@SerializedName”有什么作用?再次感谢!
    • 它提供了 JSON 字符串中使用的键和您希望映射到的 Java 类中的属性之间的映射。
    • 我不知道为什么有人会否决你和我的答案。我会赞成这个。这是一个不错的答案。
    • 只是一个简短的说明,以澄清我赞成的这个有用的答案。当您需要为名为“类”的 json 字段起别名时,使用 @SerializedName 注释的语法至关重要,这是一个保留的字段Java中的关键字。但是您当然不需要注释每个班级成员。如果 jason 对象字段名称是合法的,并且您可以使用与您自己的编码约定不完全匹配的字段名称,只需将您的对象成员命名为与 JSON 字段名称相同。
    【解决方案3】:

    在android中使用standard json classes

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

    【讨论】:

    • 感谢 Wieux,但不使用 Android。
    • 它不是 Android 特定的 API; Android 使用 json.org API,也可以在这里找到:json.org/java/index.html
    【解决方案4】:

    我推荐你使用 flexjson 库http://flexjson.sourceforge.net/ 恕我直言,它更简单和可用的库。我第一次使用 GSON,但后来我所有的项目都切换到了 flexjson 而不是 GSON。

    【讨论】:

    • 谢谢尤金!这看起来很有趣。下次我处理 JSON 时也会看看。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-20
    • 2011-12-27
    • 1970-01-01
    • 2018-06-04
    • 2019-01-19
    • 2015-04-04
    相关资源
    最近更新 更多