【问题标题】:JSON array to multiple objectsJSON数组到多个对象
【发布时间】:2021-02-28 02:48:15
【问题描述】:

我有一个如下所示的JSON 文件:

[
  {
    "request": {
      "url": "/v1/charges",
      "headers": {
        "X-sq-Client-User-Agent": "{\"lang\": \"ruby\", \"publisher\": \"sq\", \"uname\": \"Linux version 3.13.0-57-generic (buildd@brownie) (gcc version 4.8.2 (Ubuntu 4.8.2-19ubuntu1) ) #95-Ubuntu SMP Fri Jun 19 09:28:15 UTC 2015\", \"hostname\": \"caron\", \"lang_version\": \"2.1.2 p95 (2014-05-08)\", \"engine\": \"ruby\", \"platform\": \"x86_64-linux\", \"bindings_version\": \"1.23.0\"}",
        "Host": "google.com",
        "Accept-Encoding": "gzip, deflate",
        "Authorization": "Bearer xOEwT736mUYLIx7hs0xTiCkI",
        "Content-Type": "application/x-www-form-urlencoded",
        "Accept": "*/*; q=0.5, application/xml"
      },
      "body": "amount=123&currency=usd&card[number]=4242424242424242&card[exp_month]=12&card[exp_year]=2020",
      "method": "POST"
    },
    "response": {
      "body": "{\n  \"id\": \"ch_16T3toKv5xscqGyh90sf8TSa\",\n  \"amount\": 123,\n  \"amount_refunded\": 0,\n  \"application_fee\": null,\n  \"balance_transaction\": \"txn_16T3toKv5xscqGyhqAKF6jOq\",\n  \"captured\": true,\n  \"created\": 1437973900,\n  \"currency\": \"usd\",\n  \"customer\": null,\n  \"description\": null,\n  \"destination\": null,\n  \"dispute\": null,\n  \"failure_code\": null,\n  \"failure_message\": null,\n  \"fraud_details\": {\n  },\n  \"invoice\": null,\n  \"livemode\": false,\n  \"metadata\": {\n  },\n  \"object\": \"charge\",\n  \"paid\": true,\n  \"receipt_email\": null,\n  \"receipt_number\": null,\n  \"refunded\": false,\n  \"refunds\": {\n    \"has_more\": false,\n    \"total_count\": 0,\n    \"object\": \"list\",\n    \"data\": [\n\n    ],\n    \"url\": \"/v1/charges/ch_16T3toKv5xscqGyh90sf8TSa/refunds\"\n  },\n  \"shipping\": null,\n  \"source\": {\n    \"address_state\": null,\n    \"last4\": \"4242\",\n    \"dynamic_last4\": null,\n    \"address_zip_check\": null,\n    \"address_country\": null,\n    \"id\": \"card_16T3toKv5xscqGyh4LZ6rPyz\",\n    \"address_line2\": null,\n    \"address_line1\": null,\n    \"funding\": \"credit\",\n    \"metadata\": {\n    },\n    \"cvc_check\": null,\n    \"exp_month\": 12,\n    \"tokenization_method\": null,\n    \"address_line1_check\": null,\n    \"brand\": \"Visa\",\n    \"object\": \"card\",\n    \"fingerprint\": \"70RrlzfthHpu3e4l\",\n    \"exp_year\": 2020,\n    \"address_zip\": null,\n    \"customer\": null,\n    \"address_city\": null,\n    \"name\": null,\n    \"country\": \"US\"\n  },\n  \"statement_descriptor\": null,\n  \"status\": \"succeeded\"\n}",
      "headers": {
        "Content-Length": "1422",
        "Request-Id": "req_6gQly7HiMYbIEC",
        "Strict-Transport-Security": "max-age=31556926; includeSubDomains",
        "Server": "nginx",
        "Connection": "keep-alive",
        "Cache-Control": "no-cache, no-store",
        "Date": "Mon, 27 Jul 2015 05:11:40 GMT",
        "Access-Control-Allow-Credentials": "true",
        "Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS, DELETE",
        "Content-Type": "application/json",
        "Access-Control-Allow-Origin": "*"
      },
      "code": 200
    }
  },
  {
    "request": {
      "url": "/v1/charges",
      "headers": {
        "X-sq-Client-User-Agent": "{\"lang\": \"ruby\", \"publisher\": \"sq\", \"uname\": \"Linux version 3.13.0-57-generic (buildd@brownie) (gcc version 4.8.2 (Ubuntu 4.8.2-19ubuntu1) ) #95-Ubuntu SMP Fri Jun 19 09:28:15 UTC 2015\", \"hostname\": \"caron\", \"lang_version\": \"2.1.2 p95 (2014-05-08)\", \"engine\": \"ruby\", \"platform\": \"x86_64-linux\", \"bindings_version\": \"1.23.0\"}",
        "Host": "google.com",
        "Accept-Encoding": "gzip, deflate",
        "Authorization": "Bearer xOEwT736mUYLIx7hs0xTiCkI",
        "Content-Type": "application/x-www-form-urlencoded",
        "Accept": "*/*; q=0.5, application/xml"
      },
      "body": "amount=123&currency=usd&card[number]=4242424242424242&card[exp_month]=12&card[exp_year]=2020",
      "method": "POST"
    },
    "response": {
      "body": "{\n  \"id\": \"ch_16T3toKv5xscqGyh90sf8TSa\",\n  \"amount\": 123,\n  \"amount_refunded\": 0,\n  \"application_fee\": null,\n  \"balance_transaction\": \"txn_16T3toKv5xscqGyhqAKF6jOq\",\n  \"captured\": true,\n  \"created\": 1437973900,\n  \"currency\": \"usd\",\n  \"customer\": null,\n  \"description\": null,\n  \"destination\": null,\n  \"dispute\": null,\n  \"failure_code\": null,\n  \"failure_message\": null,\n  \"fraud_details\": {\n  },\n  \"invoice\": null,\n  \"livemode\": false,\n  \"metadata\": {\n  },\n  \"object\": \"charge\",\n  \"paid\": true,\n  \"receipt_email\": null,\n  \"receipt_number\": null,\n  \"refunded\": false,\n  \"refunds\": {\n    \"has_more\": false,\n    \"total_count\": 0,\n    \"object\": \"list\",\n    \"data\": [\n\n    ],\n    \"url\": \"/v1/charges/ch_16T3toKv5xscqGyh90sf8TSa/refunds\"\n  },\n  \"shipping\": null,\n  \"source\": {\n    \"address_state\": null,\n    \"last4\": \"4242\",\n    \"dynamic_last4\": null,\n    \"address_zip_check\": null,\n    \"address_country\": null,\n    \"id\": \"card_16T3toKv5xscqGyh4LZ6rPyz\",\n    \"address_line2\": null,\n    \"address_line1\": null,\n    \"funding\": \"credit\",\n    \"metadata\": {\n    },\n    \"cvc_check\": null,\n    \"exp_month\": 12,\n    \"tokenization_method\": null,\n    \"address_line1_check\": null,\n    \"brand\": \"Visa\",\n    \"object\": \"card\",\n    \"fingerprint\": \"70RrlzfthHpu3e4l\",\n    \"exp_year\": 2020,\n    \"address_zip\": null,\n    \"customer\": null,\n    \"address_city\": null,\n    \"name\": null,\n    \"country\": \"US\"\n  },\n  \"statement_descriptor\": null,\n  \"status\": \"succeeded\"\n}",
      "headers": {
        "Content-Length": "1422",
        "Request-Id": "req_6gQly7HiMYbIEC",
        "Strict-Transport-Security": "max-age=31556926; includeSubDomains",
        "Server": "nginx",
        "Connection": "keep-alive",
        "Cache-Control": "no-cache, no-store",
        "Date": "Mon, 27 Jul 2015 05:11:40 GMT",
        "Access-Control-Allow-Credentials": "true",
        "Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS, DELETE",
        "Content-Type": "application/json",
        "Access-Control-Allow-Origin": "*"
      },
      "code": 200
    }
  }
]

它是RequestResponse 对象的数组。

我想将其转换为 Java 中的 Map<Request, Response> 对象。

我创建了两个类,RequestRepsonse,如下所示:

public class Request {
    
    private String url;
    private Map<String, String> headers;
    private String body;
    private String method;
}

public class Response {
    
    private String body;
    private int code;
}

到目前为止,我有这段代码,它允许我访问文件中的单个 RequestResponse 对象。

public static void main( String[] args ) throws IOException {
    Gson gson = new Gson();
    Object[] obj = gson.fromJson(new FileReader("myJson.json"), Object[].class);
}

当我打印 obj[0] 时,它给了我这个:{request={...},response={...}}

但我无法弄清楚如何从该字符串访问 requestresponse 对象,以便我可以将它们转换为我创建的 RequestResponse 类。

任何帮助将不胜感激!谢谢!

【问题讨论】:

    标签: java json parsing


    【解决方案1】:

    Gson 无法知道您要使用您的 RequestResponse 类,因为您已要求它将 JSON 转换为 Object[]

    我会制作一个与您的数据匹配的简单 POJO:

        public static class RequestResponsePair {
            private Request request;
            private Response response;
        }
    

    然后你可以这样做:

    List<RequestResponsePair> obj2 = gson.fromJson(new FileReader("myJson.json"), new TypeToken<List<RequestResponsePair>>() {}.getType());
    Map<Request,Response> result = obj2.stream().collect(Collectors.toMap(p -> p.request, p -> p.response));
    

    现在Gson 知道您想要的类型,它可以创建您的类的实例并进行字段映射。

    【讨论】:

    • 我正在编写一个使用自定义序列化程序的方法,然后......这个。简单得多。感谢您指出这种方法
    猜你喜欢
    • 1970-01-01
    • 2013-07-16
    • 2018-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-31
    • 1970-01-01
    • 2020-10-04
    相关资源
    最近更新 更多