使用 GSON 将 JSON 解析为 Java POJO

发布于 2024-09-27 14:26:53 字数 3076 浏览 4 评论 0原文

我在这里有一个非常直接的问题。我需要从 API 获取 JSON 并将其转换为我为它们创建的对象。

到目前为止,它会将它们反序列化到我的列表中,但每个 Metric 对象都有空值

JSON COMING IN

{
"metrics": [
    {
        "metric": {
            "type": 1,
            "name": "slide-11-start",
            "value": "1287249598295",
            "sessionID": "" 
        } 
    },
    {
        "metric": {
            "type": 1,
            "name": "slide-21-start",
            "value": "1287249601368",
            "sessionID": "" 
        } 
    },
    {
        "metric": {
            "type": 7,
            "name": "resolution",
            "value": "1680x1050",
            "sessionID": "" 
        } 
    },
    {
        "metric": {
            "type": 6,
            "name": "OS",
            "value": "Linux",
            "sessionID": "" 
        } 
    },
    {
        "metric": {
            "type": 5,
            "name": "browser",
            "value": "Netscape",
            "sessionID": "" 
        } 
    } 
]

}

Metric Object

public class Metric {

    private int type;
    private String name;
    private String value;
    private String sessionID;

    /**
     * @return the type
     */
    public int getType() {
        return type;
    }

    /**
     * @param type the type to set
     */
    public void setType(int type) {
        this.type = type;
    }

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * @return the value
     */
    public String getValue() {
        return value;
    }

    /**
     * @param value the value to set
     */
    public void setValue(String value) {
        this.value = value;
    }

    /**
     * @return the sessionID
     */
    public String getSessionID() {
        return sessionID;
    }

    /**
     * @param sessionID the sessionID to set
     */
    public void setSessionID(String sessionID) {
        this.sessionID = sessionID;
    }

}

Container Ojbect

import java.util.List;

/**
 *
 * @author joshua
 */
public class MetricSet {

    private List<Metric> metrics;

    /**
     * @return the metrics
     */
    public List<Metric> getMetrics() {
        return metrics;
    }

    /**
     * @param metrics the metrics to set
     */
    public void setMetrics(List<Metric> metrics) {
        this.metrics = metrics;
    }
}

CODE转换 JSON

    String json = "";
    if(request.getParameter("data") != null) {
        json = request.getParameter("data");
    }

    MetricSet metrics = new MetricSet();

    try {
        Gson gson = new Gson();
        Type listType = new TypeToken<MetricSet>() {}.getType();
        metrics = gson.fromJson(json, MetricSet.class);
    }
    catch(Exception ex) {
        String msg = ex.toString();
    }

I have a very straight forward issue here. I need to take JSON coming from the API and convert it to objects I created for them.

This far, it will deserialize them into my List but each Metric object has null values

JSON COMING IN

{
"metrics": [
    {
        "metric": {
            "type": 1,
            "name": "slide-11-start",
            "value": "1287249598295",
            "sessionID": "" 
        } 
    },
    {
        "metric": {
            "type": 1,
            "name": "slide-21-start",
            "value": "1287249601368",
            "sessionID": "" 
        } 
    },
    {
        "metric": {
            "type": 7,
            "name": "resolution",
            "value": "1680x1050",
            "sessionID": "" 
        } 
    },
    {
        "metric": {
            "type": 6,
            "name": "OS",
            "value": "Linux",
            "sessionID": "" 
        } 
    },
    {
        "metric": {
            "type": 5,
            "name": "browser",
            "value": "Netscape",
            "sessionID": "" 
        } 
    } 
]

}

Metric Object

public class Metric {

    private int type;
    private String name;
    private String value;
    private String sessionID;

    /**
     * @return the type
     */
    public int getType() {
        return type;
    }

    /**
     * @param type the type to set
     */
    public void setType(int type) {
        this.type = type;
    }

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * @return the value
     */
    public String getValue() {
        return value;
    }

    /**
     * @param value the value to set
     */
    public void setValue(String value) {
        this.value = value;
    }

    /**
     * @return the sessionID
     */
    public String getSessionID() {
        return sessionID;
    }

    /**
     * @param sessionID the sessionID to set
     */
    public void setSessionID(String sessionID) {
        this.sessionID = sessionID;
    }

}

Container Ojbect

import java.util.List;

/**
 *
 * @author joshua
 */
public class MetricSet {

    private List<Metric> metrics;

    /**
     * @return the metrics
     */
    public List<Metric> getMetrics() {
        return metrics;
    }

    /**
     * @param metrics the metrics to set
     */
    public void setMetrics(List<Metric> metrics) {
        this.metrics = metrics;
    }
}

CODE TO CONVERT THE JSON

    String json = "";
    if(request.getParameter("data") != null) {
        json = request.getParameter("data");
    }

    MetricSet metrics = new MetricSet();

    try {
        Gson gson = new Gson();
        Type listType = new TypeToken<MetricSet>() {}.getType();
        metrics = gson.fromJson(json, MetricSet.class);
    }
    catch(Exception ex) {
        String msg = ex.toString();
    }

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

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

发布评论

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

评论(2

﹉夏雨初晴づ 2024-10-04 14:26:53

您可以为 JSON 对象创建相应的 java 类。 integerstring 值可以按原样映射。 JSON 可以这样解析:

 Gson gson = new GsonBuilder().create();
 Response r = gson.fromJson(jsonString, Response.class);

这是一个示例: http://rowsandcolumns.blogspot.com/2013/02/url-encode-http-get-solr-request-and.html

You can create corresponding java classes for the JSON objects. The integer, string values can be mapped as is. JSON can be parsed like this:

 Gson gson = new GsonBuilder().create();
 Response r = gson.fromJson(jsonString, Response.class);

Here is an example: http://rowsandcolumns.blogspot.com/2013/02/url-encode-http-get-solr-request-and.html

浊酒尽余欢 2024-10-04 14:26:53

(才 7.5 个月。)

问题是您尝试反序列化的类结构与 JSON 结构不匹配。

以下是一个用于反序列化所提供的 JSON 的简单示例。输出是

[Metrics: [
[MetricContainer: [Metric: type=1, name=slide-11-start, value=1287249598295, sessionID=]], 
[MetricContainer: [Metric: type=1, name=slide-21-start, value=1287249601368, sessionID=]], 
[MetricContainer: [Metric: type=7, name=resolution, value=1680x1050, sessionID=]], 
[MetricContainer: [Metric: type=6, name=OS, value=Linux, sessionID=]], 
[MetricContainer: [Metric: type=5, name=browser, value=Netscape, sessionID=]]]]
public class Foo
{
  static String jsonInput = 
    "{" + 
      "\"metrics\":" +
      "[" + 
        "{" + 
          "\"metric\":" +
          "{" + 
            "\"type\":1," + 
            "\"name\":\"slide-11-start\"," + 
            "\"value\":\"1287249598295\"," + 
            "\"sessionID\":\"\"" + 
          "}" + 
        "}," + 
        "{" + 
          "\"metric\":" +
          "{" + 
            "\"type\":1," + 
            "\"name\":\"slide-21-start\"," + 
            "\"value\":\"1287249601368\"," + 
            "\"sessionID\":\"\"" + 
          "}" + 
        "}," + 
        "{" + 
          "\"metric\":" +
          "{" + 
            "\"type\":7," + 
            "\"name\":\"resolution\"," + 
            "\"value\":\"1680x1050\"," + 
            "\"sessionID\":\"\"" + 
          "}" + 
        "}," + 
        "{" + 
          "\"metric\":" +
          "{" + 
            "\"type\":6," + 
            "\"name\":\"OS\"," + 
            "\"value\":\"Linux\"," + 
            "\"sessionID\":\"\"" + 
          "}" + 
        "}," + 
        "{" + 
          "\"metric\":" +
          "{" + 
            "\"type\":5," + 
            "\"name\":\"browser\"," + 
            "\"value\":\"Netscape\"," + 
            "\"sessionID\":\"\"" + 
          "}" + 
        "}" +  
      "]" + 
    "}";

  public static void main(String[] args)
  {
    GsonBuilder gsonBuilder = new GsonBuilder();
    Gson gson = gsonBuilder.create();
    Metrics metrics = gson.fromJson(jsonInput, Metrics.class);
    System.out.println(metrics);
  }
}

class Metrics 
{
  private List<MetricContainer> metrics;

  @Override
  public String toString()
  {
    return String.format(
        "[Metrics: %1$s]", 
        metrics);
  }
}

class MetricContainer
{
  private Metric metric;

  @Override
  public String toString()
  {
    return String.format(
        "[MetricContainer: %1$s]", 
        metric);
  }
}

class Metric 
{  
  private int type;
  private String name;
  private String value;
  private String sessionID;

  @Override
  public String toString()
  {
    return String.format(
        "[Metric: type=%1$d, name=%2$s, value=%3$s, sessionID=%4$s]", 
        type, name, value, sessionID);
  }
}

(It's only been 7.5 months.)

The problem is that the class structure you're trying to deserialize to doesn't match the JSON structure.

Following is a simple example that works to deserialize the JSON provided. The output is

[Metrics: [
[MetricContainer: [Metric: type=1, name=slide-11-start, value=1287249598295, sessionID=]], 
[MetricContainer: [Metric: type=1, name=slide-21-start, value=1287249601368, sessionID=]], 
[MetricContainer: [Metric: type=7, name=resolution, value=1680x1050, sessionID=]], 
[MetricContainer: [Metric: type=6, name=OS, value=Linux, sessionID=]], 
[MetricContainer: [Metric: type=5, name=browser, value=Netscape, sessionID=]]]]
public class Foo
{
  static String jsonInput = 
    "{" + 
      "\"metrics\":" +
      "[" + 
        "{" + 
          "\"metric\":" +
          "{" + 
            "\"type\":1," + 
            "\"name\":\"slide-11-start\"," + 
            "\"value\":\"1287249598295\"," + 
            "\"sessionID\":\"\"" + 
          "}" + 
        "}," + 
        "{" + 
          "\"metric\":" +
          "{" + 
            "\"type\":1," + 
            "\"name\":\"slide-21-start\"," + 
            "\"value\":\"1287249601368\"," + 
            "\"sessionID\":\"\"" + 
          "}" + 
        "}," + 
        "{" + 
          "\"metric\":" +
          "{" + 
            "\"type\":7," + 
            "\"name\":\"resolution\"," + 
            "\"value\":\"1680x1050\"," + 
            "\"sessionID\":\"\"" + 
          "}" + 
        "}," + 
        "{" + 
          "\"metric\":" +
          "{" + 
            "\"type\":6," + 
            "\"name\":\"OS\"," + 
            "\"value\":\"Linux\"," + 
            "\"sessionID\":\"\"" + 
          "}" + 
        "}," + 
        "{" + 
          "\"metric\":" +
          "{" + 
            "\"type\":5," + 
            "\"name\":\"browser\"," + 
            "\"value\":\"Netscape\"," + 
            "\"sessionID\":\"\"" + 
          "}" + 
        "}" +  
      "]" + 
    "}";

  public static void main(String[] args)
  {
    GsonBuilder gsonBuilder = new GsonBuilder();
    Gson gson = gsonBuilder.create();
    Metrics metrics = gson.fromJson(jsonInput, Metrics.class);
    System.out.println(metrics);
  }
}

class Metrics 
{
  private List<MetricContainer> metrics;

  @Override
  public String toString()
  {
    return String.format(
        "[Metrics: %1$s]", 
        metrics);
  }
}

class MetricContainer
{
  private Metric metric;

  @Override
  public String toString()
  {
    return String.format(
        "[MetricContainer: %1$s]", 
        metric);
  }
}

class Metric 
{  
  private int type;
  private String name;
  private String value;
  private String sessionID;

  @Override
  public String toString()
  {
    return String.format(
        "[Metric: type=%1$d, name=%2$s, value=%3$s, sessionID=%4$s]", 
        type, name, value, sessionID);
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文