Consuming a nested JSON array using Spring Boot and RestTemplate - java

I am attempting to consume an API in my Spring Boot application using an HTTP GET request which returns the below JSON. The issues I'm running into are that there is a JSON array contained inside the "playerentry" level with un-named/unheaded pairs of player and team info. For Spring, one would usually create a java class for each layer of the JSON and use the #JsonProperty() annotation to specify which part of the JSON to generate the Java Objects from. Without names for pairs contained inside the JSON array, and being unsure how to properly setup the java classes for the playerentry array and contained array pairs, I have been unable to use the RestTemplate and RestTemplateBuilder to consume this JSON. Any Help would be greatly appreciated.
{
"rosterplayers": {
"lastUpdatedOn": "2018-02-25 4:24:30 PM",
"playerentry": [
{
"player": {
"ID": "10138",
"LastName": "Abrines",
"FirstName": "Alex"
},
"team": {
"ID": "96",
"City": "Oklahoma City",
"Name": "Thunder",
"Abbreviation": "OKL"
}
},
{
"player": {
"ID": "9466",
"LastName": "Acy",
"FirstName": "Quincy"
},
"team": {
"ID": "84",
"City": "Brooklyn",
"Name": "Nets",
"Abbreviation": "BRO"
}
},
{
"player": {
"ID": "9390",
"LastName": "Adams",
"FirstName": "Steven"
},
"team": {
"ID": "96",
"City": "Oklahoma City",
"Name": "Thunder",
"Abbreviation": "OKL"
}
},
{
"player": {
"ID": "9375",
"LastName": "Afflalo",
"FirstName": "Arron"
},
"team": {
"ID": "103",
"City": "Sacramento",
"Name": "Kings",
"Abbreviation": "SAC"
}
},
{
"player": {
"ID": "9357",
"LastName": "Ajinca",
"FirstName": "Alexis"
},
"team": {
"ID": "110",
"City": "New Orleans",
"Name": "Pelicans",
"Abbreviation": "NOP"
}
},
{
"player": {
"ID": "9272",
"LastName": "Aldrich",
"FirstName": "Cole"
},
"team": {
"ID": "100",
"City": "Minnesota",
"Name": "Timberwolves",
"Abbreviation": "MIN"
}
},
{
"player": {
"ID": "9480",
"LastName": "Aldridge",
"FirstName": "LaMarcus"
},
"team": {
"ID": "106",
"City": "San Antonio",
"Name": "Spurs",
"Abbreviation": "SAS"
}
},
{
"player": {
"ID": "9454",
"LastName": "Alexander",
"FirstName": "Cliff"
},
"team": {
"ID": "95",
"City": "Orlando",
"Name": "Magic",
"Abbreviation": "ORL"
}
},
{
"player": {
"ID": "9299",
"LastName": "Allen",
"FirstName": "Tony"
},
"team": {
"ID": "107",
"City": "Memphis",
"Name": "Grizzlies",
"Abbreviation": "MEM"
}
}
]
}
}

This should work
class Roasterplayers {
String lastUpdatedOn;
List<PlayerEntry> playerentry;
}
class PlayerEntry {
Player player;
Team team;
}
class Player {
#JsonProperty("ID")
String id;
#JsonProperty("LastName")
String lastName;
#JsonProperty("FirstName")
String firstName;
}
class Team {
#JsonProperty("ID")
String id;
#JsonProperty("City")
String city;
#JsonProperty("Name")
String name;
#JsonProperty("Abbreviation")
String abbreviation;
}
Make sure you have Setters and Getters for each field

Related

Save Nested JSON using Spring data jpa

I want to save data in MYSQL DB by creating Entity class and repository from scratch. I am able to save the normal String Data, Integer Data but struggling to save complex JSON data's
for instance:
[
{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters":
{
"batter":
[
{ "id": "1001", "type": "Regular" },
{ "id": "1002", "type": "Chocolate" },
{ "id": "1003", "type": "Blueberry" },
{ "id": "1004", "type": "Devil's Food" }
]
},
"topping":
[
{ "id": "5001", "type": "None" },
{ "id": "5002", "type": "Glazed" },
{ "id": "5005", "type": "Sugar" },
{ "id": "5007", "type": "Powdered Sugar" },
{ "id": "5006", "type": "Chocolate with Sprinkles" },
{ "id": "5003", "type": "Chocolate" },
{ "id": "5004", "type": "Maple" }
]
},
{
"id": "0002",
"type": "donut",
"name": "Raised",
"ppu": 0.55,
"batters":
{
"batter":
[
{ "id": "1001", "type": "Regular" }
]
},
"topping":
[
{ "id": "5001", "type": "None" },
{ "id": "5002", "type": "Glazed" },
{ "id": "5005", "type": "Sugar" },
{ "id": "5003", "type": "Chocolate" },
{ "id": "5004", "type": "Maple" }
]
},
{
"id": "0003",
"type": "donut",
"name": "Old Fashioned",
"ppu": 0.55,
"batters":
{
"batter":
[
{ "id": "1001", "type": "Regular" },
{ "id": "1002", "type": "Chocolate" }
]
},
"topping":
[
{ "id": "5001", "type": "None" },
{ "id": "5002", "type": "Glazed" },
{ "id": "5003", "type": "Chocolate" },
{ "id": "5004", "type": "Maple" }
]
}
]
How can I store such JSON's in MYSQL Db?
Should I Create Class for every nested element ?
(I would consider to switch to a NoSQL DB instead of MySQL, but okay...)
//1.
create table users_json(
id int auto_increment primary key,
details json);
2.
public interface SomeRepository extends JpaRepository<AnyEntity, Long> {
#Modifying(clearAutomatically = true)
#Query(value = "insert into users_json (details) values (:param) ", nativeQuery = true)
#Transactional
int insertValue(#Param("param") String param);}
3.
anyRepository.insertValue("{ \"page\": \"1\" , \"name\": \"Zafari\", \"os\": \"Mac\", \"spend\": 100, \"resolution\": { \"x\": 1920, \"y\": 1080 } }");
4.
SELECT id, details->'$.name' FROM users_json;
Storing JSON in MySQL is possible. You can use these 3 column types depending upon the column size.
For your Entity class :
#Entity
#Getter
#Setter
public class Test {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column(columnDefinition = "LONGTEXT") // can store upto 4GB
private String longText;
#Column(columnDefinition = "MEDIUMTEXT") // can store upto 64MB
private String mediumText;
#Column(columnDefinition = "TEXT") // can store upto 64KB
private String text;
}
For your Controller method :
#PostMapping(value = "/addData")
public void addData(#RequestBody String payload) {
testRepository.addData(payload);
}
For your Repository Class:
#Repository
public interface TestRepository extends JpaRepository<Test,Integer> {
#Modifying
#Transactional
#Query(value = "INSERT INTO test(text,medium_text,long_text) VALUE(?1,?1,?1)" ,nativeQuery = true)
void addData(String payload);
}
In MYSQL it will look like this,
It depends if you want to store your Json as String or do you want to convert it into DTO instances that are mapped to your entities and use repository to save them to DB? If you want to store JSON as a String than It shouldn't be any different from any other String. If you want to store it as Entities than you need to convert your JSON (de-serialize) into your DTOs and then work with them as regular DTOs. It doesn't matter how they where created. I just answered very similar question. Please see here

Build JSON from a very complex JSON Schema in Java

I have a complex issue here and some advice or suggestions would be greatly appreciated. Essentially I have a complex JSON schema that looks something like this:
{
"$schema": "http://example.org",
"$id": "http://example.org",
"title": "schema title",
"description": "description",
"properties": {
"name": {
"description": "description",
"type": "string",
"enum": [
"name1",
"name2"
]
},
"storage": {
"description": "description",
"type": "integer",
"minimum": "200",
"maximum": "500",
"default": "200",
},
"domain": {
"description": "description",
"type": "string"
},
},
"if": {
"properties": {
"name": {
"const": "name1"
}
}
},
"then": {
"if": {
"properties": {
"version": {
"const": "version1"
}
}
},
"then": {
"properties": {
"cpus": {
"description": "description",
"type": "integer",
"minimum": 1,
"maximum": 8
},
"memory": {
"description": "description",
"type": "integer",
"minimum": 1,
"maximum": 32
},
},
"required": [
"cpus",
"memory"
]
},
"else": {
"if": {
"properties": {
"version": {
"const": "version2"
}
}
},
"then": {
"properties": {
"cpus": {
"description": "description",
"type": "integer",
"minimum": 1,
"maximum": 8
},
"diskSize": {
"description": "description",
"type": "integer",
"minimum": 250,
"maximum": 1000
},
},
"required": [
"cpus",
"diskSize"
]
}
}
},
"else": {
"if": {
"properties": {
"name": {
"const": "name2"
}
}
},
"then": {
"if": {
"properties": {
"version": {
"const": "version3"
}
}
},
"then": {
"properties": {
"diskSize": {
"description": "description",
"type": "integer",
"minimum": 100,
"maximum": 500
}
"memory": {
"description": "description",
"type": "integer",
"minimum": 1,
"maximum": 28
}
},
"required": [
"diskSize",
"memory"
]
},
"else": {
"if": {
"properties": {
"version": {
"const": "version4"
}
}
},
"then": {
"properties": {
"cpus": {
"description": "description",
"type": "integer",
"minimum": 1,
"maximum": 28
},
"memory": {
"description": "description",
"type": "integer",
"minimum": 1,
"maximum": 64
}
},
"required": [
"cpus",
"memory"
]
}
}
}
}
}
I need to build a JSON object using this schema in java. Every property in the schema is inside of a map that I have access to, so I can quite simply just get the property from the map and add it to a JsonNode object that I am building. Every property under the initial "properties" object is easy to retrieve, I can just get a list of them and then get each one from the map.
The complexity lies in the if/then/else part of the json schema. The only way I can see to find which property I need is to first build the initial part of the json from the first "properties" object and then have some sort of quite complex recursive algorithm that goes into every if/then/else statement and compares the value of the property being evaluated and then returns a list of the properties I need to get from the map. I have looked around online for a library that can build Json from a Json schema in java but haven't found anything that can deal with the complex if/then/else statements.
Any suggestions or ideas would be greatly appreciated.

will spring-data-rest expose methods in QueryByExampleExecutor interface?

i just learned how to use spring-data-rest to expose methods in repository. i wonder will the spring-data-rest expose methods in QueryByExampleExecutor<T>interface.if not, is there anyway to expose those methods. thx :).
i have a repository class that extend JpaRepository and i did not find any Restful api like methods in QueryByExampleExecutor<T> with resource discovery api.
this is what i got from resource discovery api
{
"alps": {
"version": "1.0",
"descriptor": [
{
"id": "studentEntity-representation",
"href": "http://127.0.0.1:8080/data/profile/studentEntities",
"descriptor": [
{
"name": "name",
"type": "SEMANTIC"
},
{
"name": "age",
"type": "SEMANTIC"
},
{
"name": "height",
"type": "SEMANTIC"
},
{
"name": "weight",
"type": "SEMANTIC"
},
{
"name": "hasPassed",
"type": "SEMANTIC"
}
]
},
{
"id": "create-studentEntities",
"name": "studentEntities",
"type": "UNSAFE",
"descriptor": [],
"rt": "#studentEntity-representation"
},
{
"id": "get-studentEntities",
"name": "studentEntities",
"type": "SAFE",
"descriptor": [
{
"name": "page",
"type": "SEMANTIC",
"doc": {
"format": "TEXT",
"value": "The page to return."
}
},
{
"name": "size",
"type": "SEMANTIC",
"doc": {
"format": "TEXT",
"value": "The size of the page to return."
}
},
{
"name": "sort",
"type": "SEMANTIC",
"doc": {
"format": "TEXT",
"value": "The sorting criteria to use to calculate the content of the page."
}
}
],
"rt": "#studentEntity-representation"
},
{
"id": "delete-studentEntity",
"name": "studentEntity",
"type": "IDEMPOTENT",
"descriptor": [],
"rt": "#studentEntity-representation"
},
{
"id": "update-studentEntity",
"name": "studentEntity",
"type": "IDEMPOTENT",
"descriptor": [],
"rt": "#studentEntity-representation"
},
{
"id": "get-studentEntity",
"name": "studentEntity",
"type": "SAFE",
"descriptor": [],
"rt": "#studentEntity-representation"
},
{
"id": "patch-studentEntity",
"name": "studentEntity",
"type": "UNSAFE",
"descriptor": [],
"rt": "#studentEntity-representation"
}
]
}
}

Serialization of the received stratistics into a json file

Good afternoon! I am new to JAVA and JSON. I'm using Jackson. The program does the following from the incoming JSON file:
Gives out a list of people between the ages of 20 and 30;
Unique list of cities;
The number of people with an age interval of 0-10, 11-20, 21-30, etc.
The program consists of two classes
Main.java
package com.testsample;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
try {
List<Data> data = Arrays.asList(mapper.readValue(Paths.get("C:\\dataClients.json").toFile(), Data[].class));
List<Data> age20to30 = data
.stream()
.filter(p -> p.getAge() >= 20 && p.getAge() < 30)
.sorted(Comparator.comparing(p -> p.getLastName() + " " + p.getFirstName()))
.collect(Collectors.toList());
age20to30.forEach(System.out::println);
Set<String> cities = data
.stream()
.map(Data::getCity)
.collect(Collectors.toCollection(TreeSet::new));
cities.forEach(System.out::println);
Map<String, Long> byAges = data
.stream()
.collect(Collectors.groupingBy(Data::getAgeGroup, TreeMap::new, Collectors.counting()));
System.out.println(byAges);
} catch (JsonParseException jsonParseException) {
jsonParseException.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Data.java
package com.testsample;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.time.LocalDate;
import java.time.Period;
public class Data {
private int id;
private String firstName;
private String lastName;
private LocalDate dateOfBirth;
private String city;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
Data() {
}
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
public LocalDate getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(LocalDate dob) {
if (dob.isAfter(LocalDate.now())) {
dob = dob.minusYears(100);
}
this.dateOfBirth = dob;
}
public Data(int id, String firstName, String lastName, String city, LocalDate dateOfBirth) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.city = city;
this.dateOfBirth = dateOfBirth;
}
#JsonIgnore
public int getAge() {
return Period.between(dateOfBirth, LocalDate.now()).getYears();
}
#JsonIgnore
public String getAgeGroup() {
int age = getAge();
if (age < 11) {
return "0..10";
}
return (age / 10 * 10 + 1) + ".." + ((age / 10 + 1) * 10);
}
#Override
public String toString() {
return "[id = " + id + ", age=" + getAge() + ", firstName = " + firstName + ", lastName = " + lastName + ", dateOfBirth = " + dateOfBirth + ", city = " + city + "]";
}
}
Json file
[
{
"id": "1",
"firstName": "Lesley",
"lastName": "Bryan",
"dateOfBirth": "1961-11-28",
"city": "Southampton–Portsmouth"
},
{
"id": "2",
"firstName": "Edward",
"lastName": "Houston",
"dateOfBirth": "1992-10-05",
"city": "Southampton–Portsmouth"
},
{
"id": "3",
"firstName": "Donald",
"lastName": "Ross",
"dateOfBirth": "1979-12-10",
"city": "Glasgow"
},
{
"id": "4",
"firstName": "Peter",
"lastName": "Kelly",
"dateOfBirth": "2004-03-17",
"city": "Birmingham–Wolverhampton"
},
{
"id": "5",
"firstName": "Anthony",
"lastName": "McKinney",
"dateOfBirth": "1968-03-06",
"city": "Liverpool"
},
{
"id": "6",
"firstName": "David",
"lastName": "Stewart",
"dateOfBirth": "1973-04-11",
"city": "Leeds–Bradford"
},
{
"id": "7",
"firstName": "Christopher",
"lastName": "Austin",
"dateOfBirth": "1974-12-28",
"city": "Birmingham–Wolverhampton"
},
{
"id": "8",
"firstName": "Alvin",
"lastName": "Hodge",
"dateOfBirth": "1958-11-25",
"city": "Newcastle upon Tyne–Sunderland"
},
{
"id": "9",
"firstName": "Gerald",
"lastName": "Higgins",
"dateOfBirth": "1955-06-28",
"city": "Liverpool"
},
{
"id": "10",
"firstName": "Amos",
"lastName": "Owens",
"dateOfBirth": "2001-01-16",
"city": "Manchester-Salford"
},
{
"id": "11",
"firstName": "Christian",
"lastName": "Bishop",
"dateOfBirth": "1950-11-14",
"city": "Nottingham"
},
{
"id": "12",
"firstName": "Robert",
"lastName": "Caldwell",
"dateOfBirth": "1980-12-08",
"city": "Manchester-Salford"
},
{
"id": "13",
"firstName": "Brian",
"lastName": "Heath",
"dateOfBirth": "2002-09-23",
"city": "Newcastle upon Tyne–Sunderland"
},
{
"id": "14",
"firstName": "Mark",
"lastName": "Anthony",
"dateOfBirth": "1992-01-08",
"city": "London"
},
{
"id": "15",
"firstName": "Mark",
"lastName": "Watson",
"dateOfBirth": "1991-07-27",
"city": "Nottingham"
},
{
"id": "16",
"firstName": "Charles",
"lastName": "Stafford",
"dateOfBirth": "1990-01-26",
"city": "Birmingham–Wolverhampton"
},
{
"id": "17",
"firstName": "Steven",
"lastName": "Merritt",
"dateOfBirth": "1963-12-04",
"city": "Leeds–Bradford"
},
{
"id": "18",
"firstName": "John",
"lastName": "Holmes",
"dateOfBirth": "1952-04-22",
"city": "Southampton–Portsmouth"
},
{
"id": "19",
"firstName": "Mervin",
"lastName": "Lewis",
"dateOfBirth": "1995-10-27",
"city": "Birmingham–Wolverhampton"
},
{
"id": "20",
"firstName": "Peter",
"lastName": "Marsh",
"dateOfBirth": "1963-12-10",
"city": "Glasgow"
},
{
"id": "21",
"firstName": "Piers",
"lastName": "Harrington",
"dateOfBirth": "1985-04-27",
"city": "London"
},
{
"id": "22",
"firstName": "Matthew",
"lastName": "O’Brien’",
"dateOfBirth": "1959-01-19",
"city": "Manchester-Salford"
},
{
"id": "23",
"firstName": "Blaze",
"lastName": "Williamson",
"dateOfBirth": "1959-11-26",
"city": "Leeds–Bradford"
},
{
"id": "24",
"firstName": "Ethan",
"lastName": "Harrison",
"dateOfBirth": "1999-08-27",
"city": "Southampton–Portsmouth"
},
{
"id": "25",
"firstName": "Blake",
"lastName": "Dennis",
"dateOfBirth": "2003-09-12",
"city": "Manchester-Salford"
},
{
"id": "26",
"firstName": "Isaac",
"lastName": "Jordan",
"dateOfBirth": "1994-08-08",
"city": "London"
},
{
"id": "27",
"firstName": "Winfred",
"lastName": "Washington",
"dateOfBirth": "1977-04-24",
"city": "Sheffield"
},
{
"id": "28",
"firstName": "Brent",
"lastName": "Hoover",
"dateOfBirth": "1986-09-28",
"city": "Sheffield"
},
{
"id": "29",
"firstName": "Jacob",
"lastName": "Benson",
"dateOfBirth": "1954-12-04",
"city": "Sheffield"
},
{
"id": "30",
"firstName": "Thomas",
"lastName": "Martin",
"dateOfBirth": "1954-11-18",
"city": "London"
},
{
"id": "31",
"firstName": "Ferdinand",
"lastName": "Douglas",
"dateOfBirth": "1989-01-28",
"city": "Southampton–Portsmouth"
},
{
"id": "32",
"firstName": "Cecil",
"lastName": "Sutton",
"dateOfBirth": "1982-08-16",
"city": "Leeds–Bradford"
},
{
"id": "33",
"firstName": "Peter",
"lastName": "Warner",
"dateOfBirth": "1950-03-13",
"city": "Birmingham–Wolverhampton"
},
{
"id": "34",
"firstName": "Williamя",
"lastName": "Gallagher",
"dateOfBirth": "1997-01-04",
"city": "Nottingham"
},
{
"id": "35",
"firstName": "Frank",
"lastName": "Hensley",
"dateOfBirth": "1980-03-15",
"city": "Sheffield"
},
{
"id": "36",
"firstName": "David",
"lastName": "Summers",
"dateOfBirth": "1981-08-01",
"city": "Sheffield"
},
{
"id": "37",
"firstName": "Melvin",
"lastName": "Allison",
"dateOfBirth": "1982-10-08",
"city": "Newcastle upon Tyne–Sunderland"
},
{
"id": "38",
"firstName": "Robert",
"lastName": "Bell",
"dateOfBirth": "1966-06-27",
"city": "Glasgow"
},
{
"id": "39",
"firstName": "Edward",
"lastName": "Gordon",
"dateOfBirth": "1986-07-20",
"city": "Newcastle upon Tyne–Sunderland"
},
{
"id": "40",
"firstName": "Charles",
"lastName": "Hicks",
"dateOfBirth": "1960-06-12",
"city": "Newcastle upon Tyne–Sunderland"
},
{
"id": "41",
"firstName": "Joshua",
"lastName": "Wheeler",
"dateOfBirth": "1979-02-11",
"city": "Southampton–Portsmouth"
},
{
"id": "42",
"firstName": "Leonard",
"lastName": "Hall",
"dateOfBirth": "1974-09-16",
"city": "Southampton–Portsmouth"
},
{
"id": "43",
"firstName": "Jerome",
"lastName": "Hill",
"dateOfBirth": "2002-06-04",
"city": "Liverpool"
},
{
"id": "44",
"firstName": "Matthew",
"lastName": "Hawkins",
"dateOfBirth": "1968-02-22",
"city": "Birmingham–Wolverhampton"
},
{
"id": "45",
"firstName": "Archibald",
"lastName": "Russell",
"dateOfBirth": "1965-10-29",
"city": "Manchester-Salford"
},
{
"id": "46",
"firstName": "Charles",
"lastName": "Little",
"dateOfBirth": "1954-09-07",
"city": "Glasgow"
},
{
"id": "47",
"firstName": "Neil",
"lastName": "Dean",
"dateOfBirth": "1979-12-31",
"city": "Sheffield"
},
{
"id": "48",
"firstName": "Jeremy",
"lastName": "Norris",
"dateOfBirth": "1955-07-21",
"city": "Glasgow"
},
{
"id": "49",
"firstName": "Christopher",
"lastName": "Holland",
"dateOfBirth": "1994-10-25",
"city": "Sheffield"
},
{
"id": "50",
"firstName": "Myron",
"lastName": "Carroll",
"dateOfBirth": "1982-01-16",
"city": "Glasgow"
},
{
"id": "51",
"firstName": "Hugo",
"lastName": "Long",
"dateOfBirth": "1962-05-25",
"city": "Leeds–Bradford"
},
{
"id": "52",
"firstName": "David",
"lastName": "Thornton",
"dateOfBirth": "1969-02-02",
"city": "Birmingham–Wolverhampton"
},
{
"id": "53",
"firstName": "David",
"lastName": "Eaton",
"dateOfBirth": "1960-02-27",
"city": "Southampton–Portsmouth"
},
{
"id": "54",
"firstName": "Abner",
"lastName": "Joseph",
"dateOfBirth": "1960-01-29",
"city": "Liverpool"
},
{
"id": "55",
"firstName": "Ethan",
"lastName": "McDowell",
"dateOfBirth": "1983-07-11",
"city": "Sheffield"
},
{
"id": "56",
"firstName": "Anthony",
"lastName": "Barton",
"dateOfBirth": "1972-12-09",
"city": "Glasgow"
},
{
"id": "57",
"firstName": "Anthony",
"lastName": "Green",
"dateOfBirth": "2003-01-26",
"city": "Birmingham–Wolverhampton"
},
{
"id": "58",
"firstName": "Ronald",
"lastName": "Gilbert",
"dateOfBirth": "1988-05-28",
"city": "Leeds–Bradford"
},
{
"id": "59",
"firstName": "Brendan",
"lastName": "White",
"dateOfBirth": "1975-07-02",
"city": "Glasgow"
},
{
"id": "60",
"firstName": "Christopher",
"lastName": "Richards",
"dateOfBirth": "1979-09-23",
"city": "Manchester-Salford"
},
{
"id": "61",
"firstName": "Buck",
"lastName": "Sanders",
"dateOfBirth": "1956-05-03",
"city": "Newcastle upon Tyne–Sunderland"
},
{
"id": "62",
"firstName": "Griffin",
"lastName": "Cannon",
"dateOfBirth": "1962-01-05",
"city": "Leeds–Bradford"
},
{
"id": "63",
"firstName": "Evan",
"lastName": "Nichols",
"dateOfBirth": "1960-01-18",
"city": "Birmingham–Wolverhampton"
},
{
"id": "64",
"firstName": "Peregrine",
"lastName": "Horton",
"dateOfBirth": "1960-10-11",
"city": "Liverpool"
},
{
"id": "65",
"firstName": "Paul",
"lastName": "Hampton",
"dateOfBirth": "1991-08-06",
"city": "Sheffield"
},
{
"id": "66",
"firstName": "Jacob",
"lastName": "Fox",
"dateOfBirth": "1983-05-18",
"city": "Sheffield"
},
{
"id": "67",
"firstName": "John",
"lastName": "Griffith",
"dateOfBirth": "1971-01-03",
"city": "Birmingham–Wolverhampton"
},
{
"id": "68",
"firstName": "Jack",
"lastName": "May",
"dateOfBirth": "1984-09-28",
"city": "Nottingham"
},
{
"id": "69",
"firstName": "Harold",
"lastName": "Owen",
"dateOfBirth": "1965-08-17",
"city": "Southampton–Portsmouth"
},
{
"id": "70",
"firstName": "Abraham",
"lastName": "Hardy",
"dateOfBirth": "1981-10-26",
"city": "Manchester-Salford"
},
{
"id": "71",
"firstName": "Frederick",
"lastName": "Allen",
"dateOfBirth": "1987-08-19",
"city": "London"
},
{
"id": "72",
"firstName": "Peter",
"lastName": "Thompson",
"dateOfBirth": "1992-09-27",
"city": "Sheffield"
},
{
"id": "73",
"firstName": "Bertram",
"lastName": "Hopkins",
"dateOfBirth": "2001-02-23",
"city": "London"
},
{
"id": "74",
"firstName": "Christopher",
"lastName": "Burns",
"dateOfBirth": "1962-05-22",
"city": "Manchester-Salford"
},
{
"id": "75",
"firstName": "Vernon",
"lastName": "Perry",
"dateOfBirth": "1966-10-17",
"city": "Nottingham"
},
{
"id": "76",
"firstName": "Oliver",
"lastName": "Webster",
"dateOfBirth": "1955-03-13",
"city": "Sheffield"
},
{
"id": "77",
"firstName": "Joshua",
"lastName": "Ball",
"dateOfBirth": "1972-03-08",
"city": "Manchester-Salford"
},
{
"id": "78",
"firstName": "Christopher",
"lastName": "Griffin",
"dateOfBirth": "1994-09-26",
"city": "Nottingham"
},
{
"id": "79",
"firstName": "Sherman",
"lastName": "Pearson",
"dateOfBirth": "1959-01-31",
"city": "Liverpool"
},
{
"id": "80",
"firstName": "Gavin",
"lastName": "Barber",
"dateOfBirth": "2003-02-16",
"city": "Manchester-Salford"
},
{
"id": "81",
"firstName": "Brian",
"lastName": "Mills",
"dateOfBirth": "1980-10-17",
"city": "Newcastle upon Tyne–Sunderland"
},
{
"id": "82",
"firstName": "Herbert",
"lastName": "Grant",
"dateOfBirth": "1991-11-28",
"city": "Southampton–Portsmouth"
},
{
"id": "83",
"firstName": "Christopher",
"lastName": "Sherman",
"dateOfBirth": "2002-04-08",
"city": "Sheffield"
},
{
"id": "84",
"firstName": "Patrick",
"lastName": "Morrison",
"dateOfBirth": "1979-07-13",
"city": "Glasgow"
},
{
"id": "85",
"firstName": "Kristopher",
"lastName": "Nash",
"dateOfBirth": "1966-09-10",
"city": "Newcastle upon Tyne–Sunderland"
},
{
"id": "86",
"firstName": "Henry",
"lastName": "Hood",
"dateOfBirth": "1975-10-03",
"city": "Sheffield"
},
{
"id": "87",
"firstName": "Edward",
"lastName": "Walsh",
"dateOfBirth": "2004-04-16",
"city": "Sheffield"
},
{
"id": "88",
"firstName": "Williamя",
"lastName": "Francis",
"dateOfBirth": "1969-08-06",
"city": "Newcastle upon Tyne–Sunderland"
},
{
"id": "89",
"firstName": "Leo",
"lastName": "Richardson",
"dateOfBirth": "1989-12-19",
"city": "Liverpool"
},
{
"id": "90",
"firstName": "Mark",
"lastName": "Day",
"dateOfBirth": "1954-06-06",
"city": "Leeds–Bradford"
},
{
"id": "91",
"firstName": "Charles",
"lastName": "Cross",
"dateOfBirth": "1955-02-23",
"city": "Liverpool"
},
{
"id": "92",
"firstName": "Alban",
"lastName": "Fields",
"dateOfBirth": "1953-09-03",
"city": "Liverpool"
},
{
"id": "93",
"firstName": "Paul",
"lastName": "Rodgers",
"dateOfBirth": "1966-10-07",
"city": "Sheffield"
},
{
"id": "94",
"firstName": "James",
"lastName": "Gregory",
"dateOfBirth": "1965-11-23",
"city": "London"
},
{
"id": "95",
"firstName": "Harry",
"lastName": "Patrick",
"dateOfBirth": "1967-04-27",
"city": "Southampton–Portsmouth"
},
{
"id": "96",
"firstName": "Jacob",
"lastName": "Walters",
"dateOfBirth": "1952-12-09",
"city": "Manchester-Salford"
},
{
"id": "97",
"firstName": "Kenneth",
"lastName": "Thomas",
"dateOfBirth": "1973-05-16",
"city": "Leeds–Bradford"
},
{
"id": "98",
"firstName": "Ernest",
"lastName": "Cobb",
"dateOfBirth": "1985-09-05",
"city": "Glasgow"
},
{
"id": "99",
"firstName": "Joseph",
"lastName": "Small",
"dateOfBirth": "1965-03-06",
"city": "Nottingham"
},
{
"id": "100",
"firstName": "Basil",
"lastName": "Stephens",
"dateOfBirth": "1964-07-29",
"city": "London"
}
]
The result of the program is as follows:
[id = 14, age=28, firstName = Mark, lastName = Anthony, dateOfBirth = 1992-01-08, city = London]
[id = 34, age=23, firstName = Williamя, lastName = Gallagher, dateOfBirth = 1997-01-04, city = Nottingham]
[id = 82, age=28, firstName = Herbert, lastName = Grant, dateOfBirth = 1991-11-28, city = Southampton–Portsmouth]
[id = 78, age=26, firstName = Christopher, lastName = Griffin, dateOfBirth = 1994-09-26, city = Nottingham]
[id = 65, age=29, firstName = Paul, lastName = Hampton, dateOfBirth = 1991-08-06, city = Sheffield]
[id = 24, age=21, firstName = Ethan, lastName = Harrison, dateOfBirth = 1999-08-27, city = Southampton–Portsmouth]
[id = 49, age=25, firstName = Christopher, lastName = Holland, dateOfBirth = 1994-10-25, city = Sheffield]
[id = 2, age=28, firstName = Edward, lastName = Houston, dateOfBirth = 1992-10-05, city = Southampton–Portsmouth]
[id = 26, age=26, firstName = Isaac, lastName = Jordan, dateOfBirth = 1994-08-08, city = London]
[id = 19, age=24, firstName = Mervin, lastName = Lewis, dateOfBirth = 1995-10-27, city = Birmingham–Wolverhampton]
[id = 72, age=28, firstName = Peter, lastName = Thompson, dateOfBirth = 1992-09-27, city = Sheffield]
[id = 15, age=29, firstName = Mark, lastName = Watson, dateOfBirth = 1991-07-27, city = Nottingham]
Birmingham–Wolverhampton
Glasgow
Leeds–Bradford
Liverpool
London
Manchester-Salford
Newcastle upon Tyne–Sunderland
Nottingham
Sheffield
Southampton–Portsmouth
{11..20=10, 21..30=12, 31..40=19, 41..50=16, 51..60=21, 61..70=21, 71..80=1}
Now I need to serialize all received data into one file. They tell me that I need to create another class that will collect the results of the program, and then serialize it into a json file.
Please help in the implementation of this task.
P.S.: All names, surnames and dates from the json file were obtained at random.
You can write the obtained output to HashMap and that hashMap can be written to a file using ObjectMapper like this.
package com.testsample;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
try {
List<Data> data = Arrays.asList(mapper.readValue(Paths.get("C:\\dataClients.json").toFile(), Data[].class));
List<Data> age20to30 = data
.stream()
.filter(p -> p.getAge() >= 20 && p.getAge() < 30)
.sorted(Comparator.comparing(p -> p.getLastName() + " " + p.getFirstName()))
.collect(Collectors.toList());
age20to30.forEach(System.out::println);
Set<String> cities = data
.stream()
.map(Data::getCity)
.collect(Collectors.toCollection(TreeSet::new));
cities.forEach(System.out::println);
Map<String, Long> byAges = data
.stream()
.collect(Collectors.groupingBy(Data::getAgeGroup, TreeMap::new, Collectors.counting()));
System.out.println(byAges);
Map<String, Object> map = new HashMap<>();
map.put("age20To30", age20to30);
map.put("cities", cities);
map.put("byAges", byAges);
// convert map to JSON file
mapper.writeValue(Paths.get("C:\\dataOutput.json").toFile(), map);
} catch (JsonParseException jsonParseException) {
jsonParseException.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Now the content of the output file will be like below
{
"cities": [
"Birmingham–Wolverhampton",
"Glasgow",
"Leeds–Bradford",
"Liverpool",
"London",
"Manchester-Salford",
"Newcastle upon Tyne–Sunderland",
"Nottingham",
"Sheffield",
"Southampton–Portsmouth"
],
"byAges": {
"11..20": 10,
"21..30": 12,
"31..40": 19,
"41..50": 16,
"51..60": 21,
"61..70": 21,
"71..80": 1
},
"age20To30": [
{
"id": 14,
"firstName": "Mark",
"lastName": "Anthony",
"dateOfBirth": "1992-01-08",
"city": "London"
},
{
"id": 34,
"firstName": "Williamя",
"lastName": "Gallagher",
"dateOfBirth": "1997-01-04",
"city": "Nottingham"
}
]
}

How to create RealmList<RealmList<Object>> in android

I am trying to get a RealmList of RealmList from server (JSON) into realm object. I am getting
error: Element type of RealmList must be a class implementing 'RealmModel' or one of the 'java.lang.String', 'byte[]', 'java.lang.Boolean', 'java.lang.Long', 'java.lang.Integer', 'java.lang.Short', 'java.lang.Byte', 'java.lang.Double', 'java.lang.Float', 'java.util.Date'.
{
"facilities": [
{
"facility_id": "1",
"name": "Property Type",
"options": [
{
"name": "Apartment",
"icon": "apartment",
"id": "1"
},
{
"name": "Condo",
"icon": "condo",
"id": "2"
},
{
"name": "Boat House",
"icon": "boat",
"id": "3"
},
{
"name": "Land",
"icon": "land",
"id": "4"
}
]
},
{
"facility_id": "2",
"name": "Number of Rooms",
"options": [
{
"name": "1 to 3 Rooms",
"icon": "rooms",
"id": "6"
},
{
"name": "No Rooms",
"icon": "no-room",
"id": "7"
}
]
},
{
"facility_id": "3",
"name": "Other facilities",
"options": [
{
"name": "Swimming Pool",
"icon": "swimming",
"id": "10"
},
{
"name": "Garden Area",
"icon": "garden",
"id": "11"
},
{
"name": "Garage",
"icon": "garage",
"id": "12"
}
]
}
],
"exclusions": [
[
{
"facility_id": "1",
"options_id": "4"
},
{
"facility_id": "2",
"options_id": "6"
}
],
[
{
"facility_id": "1",
"options_id": "3"
},
{
"facility_id": "3",
"options_id": "12"
}
],
[
{
"facility_id": "2",
"options_id": "7"
},
{
"facility_id": "3",
"options_id": "12"
}
]
]
}
try this solution
public class Exclusion extends RealmObject {
private int facilityId;
private int optionsId;
}
public class Exclusions extends RealmObject {
private RealmList<Exclusion> exclusions;
}
so now you can using RealmList<Exclusions> exclusionsRealmList as Realm list, legal
hope this helps
Gianthran's answer is close, but you should also set up relations.
public class Exclusion extends RealmObject {
#Index
private int facilityId;
#Index
private int optionsId;
private Facility facility;
private Option option;
}
And
public class Facility extends RealmObject {
#LinkingObjects("facility")
private final RealmResults<Exclusion> exclusions = null;
}
public class Option extends RealmObject {
#LinkingObjects("option")
private final RealmResults<Exclusion> exclusions = null;
}
I don't think the Exclusions object is necessary, I'd expect that the table is already a collection in a way.

Categories