sync101
sync101

Reputation: 45

JSON array to multiple objects

I have a JSON file that looks like this:

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

It is an array of Request and Response objects.

I want to convert this into a Map<Request, Response> object in Java.

I have created two classes, Request and Repsonse that look like this:

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

So far, I have this code, which is allows me to access the individual Request and Response objects within the file.

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

When I print obj[0] it gives me this: {request={...},response={...}}

But I am not able to figure out how to access the request and response object from that string so that I can convert them to the Request and Response classes I created.

Any help will be greatly appreciated! Thanks!

Upvotes: 1

Views: 145

Answers (1)

tgdavies
tgdavies

Reputation: 11411

Gson has no way of knowing that you want to use your Request and Response classes, as you have asked it to convert the JSON to Object[].

I would make a simple POJO which matches your data:

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

And then you can do:

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

Now that Gson knows the type you want it can create instances of your classes and do the mapping of the fields.

Upvotes: 2

Related Questions