Search code examples
javagsonndjson

Mapping multiple ndJson records with Gson



I want to map multiple records in ndJson with my DTO class. Following is my ndJson file:

// Record # 1 (This line is not included in the file and is only for clarification)
{
 "profile":{
      "salutation":"Mr",
      "title":null,
      "company":null
   }, 
   "phone":{
      "home_phone":null
   },
   "addresses":[
      {
         "address_id":"1",
         "title":"",
         "company":null,
         "salutation":null,
         "first_name":"Veronica",
         "last_name":"Costello",
         "second_name":null
      }
   ],
   "orders":{
      "placed_orders_count":2,
      "0":{
         "order_id":"000000001",
         "order_date":"2019-03-27 14:25:03"
      },
      "1":{
         "order_id":"000000002",
         "order_date":"2019-03-27 14:25:03"
      }
   },
   "customs":[
      
   ]
}

// Record # 2 (This line is not included in the file and is only for clarification)
{
    "profile":{
      "salutation":null,
      "title":null,
      "company":null,
      "job_title":null
   },
   "phone":{
      "home_phone":null,
      "business_phone":null,
      "mobile_phone":null,
      "fax_number":null
   },
   "addresses":[
      {
         "address_id":"2",
         "title":""
      }
   ],
   "orders":{
      "placed_orders_count":0
   },
   "customs":[
      
   ]
}

//Similarly the file has a lot of records

I want to map all the records but only able to map first record.

I have asked a similar question at How to Read ndJSON file in Java but I am not able to map all records with the accepted solution. Below is my code:

Gson gson = new Gson();
JsonReader reader = new JsonReader(new FileReader("customer.json"));
CustomerFeedDTO customerFeedDTO = gson.fromJson(reader, CustomerFeedDTO.class);

And Customer DTO class is:

private Map<String, ?> profile;
private Map<String, ?> phone;
private ArrayList<?> addresses;
private Map<String, ?> orders;
private ArrayList<?> customs;

// Getters and setter

But I am only getting the first record with this code. How can I map all the records into CustomerDTO object?


Solution

  • You can use reader.peek() method and apply loop on your code such that you need to make list of CustomerDTO and keep on adding object in it like:

    List<CustomerFeedDTO> customerFeedDTOs = new ArrayList<CustomerFeedDTO>();
    Gson gson = new Gson();
    JsonReader reader = new JsonReader(new FileReader("customer.json"));
    // Required
    reader.setLenient(true);
    while (reader.peek() != JsonToken.END_DOCUMENT) {
        CustomerFeedDTO customerFeedDTO = gson.fromJson(reader, CustomerFeedDTO.class);
        customerFeedDTOs.add(customerFeedDTO);
    }
    

    Note that reader also has a hasNext() method but that gives Exception when you reach at the end of the document. For further details about this, refer to https://stackoverflow.com/a/52250761/16437679