I'm trying to add multiple records in a List of List of Objects and I don't know how to do it (java).
The only way I've found it possible is by doing it literally:
List<List<Object>> values = Arrays.asList(
Arrays.asList("84935", "01/02/2020", "01/02/2020", "resolved", "XXX", "XXX", "XXX", "XXX", "1", "1", "15", "0", "2020"),
Arrays.asList("84936", "02/02/2020", "02/02/2020", "resolved", "XXX", "XXX", "XXX", "XXX", "1", "1", "15", "0", "2020"),
Arrays.asList("84937", "03/02/2020", "03/02/2020", "resolved", "XXX", "XXX", "XXX", "XXX", "1", "1", "15", "0", "2020")
);
I want to read a .csv file and write in it that list. When I try with .add or set I get a nullpointer Exception and I haven't been able to find a solution.
Is it possible to add the records automatically with a loop? It is mandatory that the List is List<List<Object>> because it's the only way that Google Sheets Api allows.
Thank you.
Yes it's absolutely possible to write a list of lists inside a loop:
For example:
List<List<String>> list = new ArrayList<>();
for (String line: lines) {
list.add(Arrays.asList(line.split(","));
}
If you're reading a CSV file you'd be better off using a third party library such as Apache CSVParser.
However if you insist on doing it yourself:
List<List<String>> fields = Files.lines(fileName)
.map(l -> Arrays.asList(l.split(",")))
.collect(Collector.toList());
Related
I am trying to access the "text" values in the below JSON and create an ArrayList with those values. How would I approach that? I am trying to use com.fasterxml.jackson.
{
"searchApiFormatVersion": "1.0",
"searchName": "SalaryAccessRole",
"description": "",
"totalRowCount": "2",
"returnedRowCount": "2",
"startingReturnedRowNumber": "1",
"basetype": "Person",
"columnCount": "1",
"columnHeaders": [
{
"text": "EMPLID",
"dataType": "string"
}
],
"resultSet": {
"rows": [
{
"values": [
{
"text": "2270127",
"dataType": "string",
"columnHeader": "EMPLID"
}
]
},
{
"values": [
{
"text": "1050518",
"dataType": "string",
"columnHeader": "EMPLID"
}
]
}
]
}
}
I've used this to success for the searchName but am trying to get the text under resultSet->rows->values->text.
JsonNode salaryExcludePersonNode = new ObjectMapper().readTree(sourceJson);
String person = salaryExcludePersonNode.get("searchName").textValue();//this works
String person2 = salaryExcludePersonNode.get("resultSet")
.get("rows")
.get("values")
.get("text")
.textValue());//this says that com.fasterxml.jackson.databind.JsonNode.get(String) is null
I know you tagged this question as a Jackson question, but I think JSONPath may be a good fit here.
The JSONPath library is available as a Maven dependency:
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.7.0</version>
</dependency>
For the JSON in your question, all of the "text" values can be selected using a single JSONPath selector:
$.resultSet.rows..text
$ - start at the root of the JSON.
.resultSet.rows - navigate to the rows array.
..text - recursively find all text entries.
The results are automatically added to a Java List:
String jsonAsString = "{...}";
List<String> textList = JsonPath.read(jsonAsString, "$.resultSet.rows..text");
You can also read from a java.io.File directly:
File jsonFile = "/your/path/to/file.json";
List<String> textList = JsonPath.read(jsonFile, "$.resultSet.rows..text");
The list will be populated with 2 entries:
2270127
1050518
References:
JSONPath syntax overview
JavaDocs
I have a json response that comes under this form.
"calendarList": [
{
"id": "1",
"event": {
"id": "11",
"name": "Track the working hours",
"color": "blue",
"place": "office",
}
},
{
"id": "2",
"event": {
"id": "12",
"name": "Finish DTOs",
"color": "blue",
"place": "office",
}
}
]
How can I access the place value? For all of dto objects inside the list the place value will be the same, which is OFFICE, so I just need to access somehow one of the place values.
The list of CalendarDto contains multiple EventDto objects, with the attributes id, name, color and place.
final List<CalendarDto> calendarList = calendarService.getCalendars(startDate, endDate);
EventDto eventDto = new EventDto();
EventSender sender = new EventSender ("EVENTS");
sender.withData("place", calendarList.stream() -> this is where I tried to get the value, but it didn't work
.findFirst(eventDto.getPlace()));
You can use combination of filter and findFirst methods of stream.
final List<CalendarDto> calendarList = calendarService.getCalendars(startDate, endDate);
EventDto eventDto = new EventDto();
EventSender sender = new EventSender ("EVENTS");
sender.withData("place", calendarList.stream()
.filter(ele -> ele.getPlace().equals(eventDto.getPlace())).findFirst());
Note:- ele into filter method will be object of CalendarDto class, here respective method is required to be replaced to get place value.
Apologies if this is a duplicate post. I am trying to find a string in the following array response basing on conditions specified.
{
"MRData": {
"xmlns": "http://ergast.com/mrd/1.4",
"series": "f1",
"url": "http://ergast.com/api/f1/2016/drivers.json",
"limit": "30",
"offset": "0",
"total": "24",
"DriverTable": {
"season": "2016",
"Drivers": [
{
"driverId": "alonso",
"permanentNumber": "14",
"code": "ALO",
"url": "http://en.wikipedia.org/wiki/Fernando_Alonso",
"givenName": "Fernando",
"familyName": "Alonso",
"dateOfBirth": "1981-07-29",
"nationality": "Spanish"
},
{
"driverId": "bottas",
"permanentNumber": "77",
"code": "BOT",
"url": "http://en.wikipedia.org/wiki/Valtteri_Bottas",
"givenName": "Valtteri",
"familyName": "Bottas",
"dateOfBirth": "1989-08-28",
"nationality": "Finnish"
},
{
"driverId": "button",
"permanentNumber": "22",
"code": "BUT",
"url": "http://en.wikipedia.org/wiki/Jenson_Button",
"givenName": "Jenson",
"familyName": "Button",
"dateOfBirth": "1980-01-19",
"nationality": "British"
}
]
}
}
}
1) I would like to find the permanent number of driverId "alonso" assuming that it doesn't come first always in each request. i.e each time the request is made the arrays reshuffle. the logic here would be to get the array count of the driverId alonso and insert that into the query below
"MRData.DriverTable.Drivers[insert the array count of alonso here].permanentNumber"
2) I would like to get the permanent numbers that are less than 20. I would also like to get the driverIds of the drivers whose permanent numbers are less than 20.
thanks a lot for viewing!
Try to build the Classes "MRData" and "Driver" with all necessary parameters.
and let org.json or GSON do the magic. You should really look at How to parse JSON in Java as Lars mentioned.
got that sorted!
answer to my first question-
public void extraResponseWithInRange(String url) {
Response response = given().when().get(url);
List<Map<String, String>> responseFromArray = JsonPath.parse(response.asString()).read("$.MRData.DriverTable.Drivers[?(#.driverId== 'alonso')]");
for (Map<String, String> rfa : responseFromArray) {
assertThat(rfa.get("permanentNumber"), equalToIgnoringCase("14"));
answer to my second question-
List<Map<String,String>> driversBetween=JsonPath.parse(response.asString()).read("$.MRData.DriverTable.Drivers[?(#.permanentNumber > '0' && #.permanentNumber <'20')]");
for(Map<String,String> dbsmall: driversBetween){
System.out.println(dbsmall.get("permanentNumber"));
}
please let me know if i could write this in a better way.
thanks a lot!
Either marshall the data into a POJO, and check the values of the fields there, or use something like [JSONPath][1].
int permanentNumber = JSONPath.read(json, "$..Drivers[?(#.driverId == 'alonso')].permanentNumber");
Disclaimer, I don't have an environment currently to run this, but their docs are pretty good.
We are migrating from mongoDB to CosmoDB using the Mongo Java Client. We have encountered the following difference in query behavior with arrays.
We have documents that look something like the following
[{
"name":"garry",
"pets":["cats","dogs"]
},
{
"name":"sally",
"pets":["cats","fish"]
}]
using mongo a query for
find({"pets":"cats"})
will return garry and sally however using cosmoDB we get zero results.
Is there a way to modify the query to replicate the same mongo behavior?
We also have documents that look something like the following that we query on type
[{
"name": "garry",
"pets": [{
"type": "cat",
"name": "Mittens"
}, {
"type": "dog",
"name": "Max"
}]
},
{
"name": "sally",
"pets": [{
"type": "cat",
"name": "Paul"
}, {
"type": "fish",
"name": "Bubbles"
}]
}
]
current mongo queries look like
find({"pets.type": "fish"})
in
I tried to use the query below, it works.
Using MongoShell.
find({"pets": {$all: ["cats"]}})
For Mongo Java Driver
FindIterable<Document> queryResult = collection.find(Filters.all("pets", "cats"));
I want to create a json structure as following:
{
"firstName": "John",
"lastName": "Smith",
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": 10021
},
"phoneNumbers": [
"212 732-1234",
"646 123-4567"
]
}
Using add property method I am able to create firstName and lastName but haven't figured out how to create address and phoneNumbers in Java.
Please help me out in this;
Ajay
What you'll need to do is create a new Class called Address which has those properties (string streetAdress, city, state, postalcode). The structure itself will then have an instance of that class.
Also I wouldn't make postalCode an int. Leave it as a string.
PhoneNumbers will be a list of strings (unless you want to do something fancy with it).