从 JSON 获取数据

发布于 2024-11-18 23:28:12 字数 456 浏览 2 评论 0原文

我试图从这个 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 中。

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

感谢您的帮助!

I'm trying to get the values out of this JSON string but I'm having a hard time achieving this.

{"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"}         
    ]}

What way would be easiest to access the data in 'Suggestions'? I'm using the GSON module. Ideally I would like to put it all in a HashMap.

Thanks for any help and/or suggestions!

Thanks for any help!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

木槿暧夏七纪年 2024-11-25 23:28:12

希望这有帮助:

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

}

Hope this helps:

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

}
倾其所爱 2024-11-25 23:28:12

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

I'm recommend you to use flexjson library http://flexjson.sourceforge.net/
IMHO, it more simple and usable library. I has used GSON first time, but then switched all my projects to flexjson instead of GSON.

你是暖光i 2024-11-25 23:28:12

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

Using the standard json classes in 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;
}
胡渣熟男 2024-11-25 23:28:12

理想情况下,我想将其全部放入 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。)

Ideally I would like to put it all in a HashMap.

If you can switch libraries, Jackson can achieve that with just one line of code.

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

This would deserialize any JSON object into a HashMap, composed of just Java SE components. I haven't yet seen another Java-to/from-JSON library that can do that.

The same can be accomplished with Gson, but it requires a few more lines of code. Here's one such solution.

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

(I copied this code from my blog post at http://programmerbruce.blogspot.com/2011/06/gson-v-jackson.html.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文