How to read JSON file to Java - java

How to write code to read and display key and value from web_block, port_block and user?
My JSON file test.json:
{
"web_block":[
{
"url" : "www.facebook.com",
"action" : "deny"
},
{
"url" : "www.google.com",
"action" : "deny"
},
{
"url" : "www.youtube.com",
"action" : "deny"
},
{
"url" : "www.wu.ac.th",
"action" : "allow"
}
],
"port_block":[
{
"port" : "80",
"protocol" : "tcp",
"action" : "block"
},
{
"port" : "443",
"protocol" : "udp",
"action" : "allow"
}
],
"user": [
{
"username" : "toms"
}
]
}
I tried following:
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("d:\\test.json"));
JSONObject jsonObject = (JSONObject) obj;
String name = (String) jsonObject.get("web_block");
System.out.println(url);
long age = (Long) jsonObject.get("port_block");
System.out.println(port);
but it is still wrong.

Add the following Jackson libraries to your project -
jackson-databind
jackson-annotations
jackson-core
Create a pojo class mapped to your json -
public class CustomJsonData{
#JsonProperty("web_block")
private List<WebBlock> webBlock = new ArrayList<WebBlock>();
#JsonProperty("port_block")
private List<PortBlock> portBlock = new ArrayList<PortBlock>();
#JsonProperty("user")
private List<User> user = new ArrayList<User>();
public CustomJsonData() {
}
public List<WebBlock> getWebBlock() {
return webBlock;
}
public void setWebBlock(List<WebBlock> webBlock) {
this.webBlock = webBlock;
}
public List<PortBlock> getPortBlock() {
return portBlock;
}
public void setPortBlock(List<PortBlock> portBlock) {
this.portBlock = portBlock;
}
public List<User> getUser() {
return user;
}
public void setUser(List<User> user) {
this.user = user;
}
}
class PortBlock {
#JsonProperty("port")
private String port;
#JsonProperty("protocol")
private String protocol;
#JsonProperty("action")
private String action;
public PortBlock() {
}
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
public String getProtocol() {
return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
}
class User {
#JsonProperty("username")
private String username;
public User() {
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
class WebBlock {
#JsonProperty("url")
private String url;
#JsonProperty("action")
private String action;
public WebBlock() {
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
}
Explanation: Data in your json present under "[ ]" is an array, so it is mapped with array list, where as data under "{ }" is an object, so it is mapped with a particular class (example: WebBlock, PortBlock etc) which is having fields of string type.
Now you can retrieve data like below -
ObjectMapper mapper = new ObjectMapper();
CustomJsonData object = mapper.readValue(new FileReader("d:\\test.json"),CustomJsonData.class);
String username = object.getUser().get(0).getUsername();
List<WebBlock> webBlocks = object.getWebBlock();
List<PortBlock> portBlocks = object.getPortBlock();
Refer the examples here - http://wiki.fasterxml.com/JacksonInFiveMinutes

Related

Unable to deserialize HATEOS JSON using RestTemplate

I am trying to call a Spring Cloud Data Flow REST Endpoint which is supposed to return a list of all the executions of a task whose name is passed in the input.
For starters, I ran the following URL in the browser :
http://dataflow-server.myhost.net/tasks/executions?task1225
The following JSON is shown on the browser :
{
"_embedded": {
"taskExecutionResourceList": [
{
"executionId": 2908,
"exitCode": 0,
"taskName": "task1225",
"startTime": "2021-06-25T18:40:24.823+0000",
"endTime": "2021-06-25T18:40:27.585+0000",
"exitMessage": null,
"arguments": [
"--spring.datasource.username=******",
"--spring.cloud.task.name=task1225",
"--spring.datasource.url=******",
"--spring.datasource.driverClassName=org.h2.Driver",
"key=******",
"batchId=20210625_025755702",
"--spring.cloud.data.flow.platformname=default",
"--spring.cloud.task.executionid=2908"
],
"jobExecutionIds": [],
"errorMessage": null,
"externalExecutionId": "task1225-kp7mvwkmll",
"parentExecutionId": null,
"resourceUrl": "Docker Resource [docker:internal.artifactrepository.myhost.net/myProject/myimage:0.1]",
"appProperties": {
"spring.datasource.username": "******",
"spring.cloud.task.name": "task1225",
"spring.datasource.url": "******",
"spring.datasource.driverClassName": "org.h2.Driver"
},
"deploymentProperties": {
"spring.cloud.deployer.kubernetes.requests.memory": "512Mi",
"spring.cloud.deployer.kubernetes.limits.cpu": "1000m",
"spring.cloud.deployer.kubernetes.limits.memory": "8192Mi",
"spring.cloud.deployer.kubernetes.requests.cpu": "100m"
},
"taskExecutionStatus": "COMPLETE",
"_links": {
"self": {
"href": "http://dataflow-server.myhost.net/tasks/executions/2908"
}
}
}
]
},
"_links": {
"first": {
"href": "http://dataflow-server.myhost.net/tasks/executions?page=0&size=20"
},
"self": {
"href": "http://dataflow-server.myhost.net/tasks/executions?page=0&size=20"
},
"next": {
"href": "http://dataflow-server.myhost.net/tasks/executions?page=1&size=20"
},
"last": {
"href": "http://dataflow-server.myhost.net/tasks/executions?page=145&size=20"
}
},
"page": {
"size": 20,
"totalElements": 2908,
"totalPages": 146,
"number": 0
}
}
Next, I tried to call the same REST endpoint through Java; however, no matter what I try, the response object seems to be empty with none of the attributes populated :
Approach 1 : Custom domain classes created to deserialize the response. (Did not work. Empty content recieved in response)
ParameterizedTypeReference<Resources<TaskExecutions>> ptr = new ParameterizedTypeReference<Resources<TaskExecutions>>() {
};
ResponseEntity<Resources<TaskExecutions>> entity = restTemplate.exchange(
"http://dataflow-server.myhost.net/tasks/executions?task1225",
HttpMethod.GET, null, ptr);
System.out.println(entity.getBody().getContent()); **//empty content**
Where, TaskExecutions domain is as follows :
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({ "taskExecutionResourceList" })
#JsonIgnoreProperties(ignoreUnknown = true)
public class TaskExecutions {
public TaskExecutions() {
}
#JsonProperty("taskExecutionResourceList")
List<TaskExecutionResource> taskExecutionResourceList = new ArrayList<>();
#JsonProperty("taskExecutionResourceList")
public List<TaskExecutionResource> getTaskExecutionResourceList() {
return taskExecutionResourceList;
}
#JsonProperty("taskExecutionResourceList")
public void setTaskExecutionResourceList(List<TaskExecutionResource> taskExecutionResourceList) {
this.taskExecutionResourceList = taskExecutionResourceList;
}
}
And TaskExecutionResource is as follows :
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"executionId",
"exitCode",
"taskName",
"startTime",
"endTime",
"exitMessage",
"arguments",
"jobExecutionIds",
"errorMessage",
"externalExecutionId",
"parentExecutionId",
"resourceUrl",
"appProperties",
"deploymentProperties",
"taskExecutionStatus",
"_links" })
#JsonIgnoreProperties(ignoreUnknown = true)
public class TaskExecutionResource {
#JsonProperty("executionId")
private Integer executionId;
#JsonProperty("exitCode")
private Integer exitCode;
#JsonProperty("taskName")
private String taskName;
#JsonProperty("startTime")
private String startTime;
#JsonProperty("endTime")
private String endTime;
#JsonProperty("exitMessage")
private Object exitMessage;
#JsonProperty("arguments")
private List<String> arguments = new ArrayList<String>();
#JsonProperty("jobExecutionIds")
private List<Object> jobExecutionIds = new ArrayList<Object>();
#JsonProperty("errorMessage")
private Object errorMessage;
#JsonProperty("externalExecutionId")
private String externalExecutionId;
#JsonProperty("parentExecutionId")
private Object parentExecutionId;
#JsonProperty("resourceUrl")
private String resourceUrl;
#JsonProperty("appProperties")
private AppProperties appProperties;
#JsonProperty("deploymentProperties")
private DeploymentProperties deploymentProperties;
#JsonProperty("taskExecutionStatus")
private String taskExecutionStatus;
#JsonProperty("_links")
private Links links;
#JsonProperty("executionId")
public Integer getExecutionId() {
return executionId;
}
#JsonProperty("executionId")
public void setExecutionId(Integer executionId) {
this.executionId = executionId;
}
#JsonProperty("exitCode")
public Integer getExitCode() {
return exitCode;
}
#JsonProperty("exitCode")
public void setExitCode(Integer exitCode) {
this.exitCode = exitCode;
}
#JsonProperty("taskName")
public String getTaskName() {
return taskName;
}
#JsonProperty("taskName")
public void setTaskName(String taskName) {
this.taskName = taskName;
}
#JsonProperty("startTime")
public String getStartTime() {
return startTime;
}
#JsonProperty("startTime")
public void setStartTime(String startTime) {
this.startTime = startTime;
}
#JsonProperty("endTime")
public String getEndTime() {
return endTime;
}
#JsonProperty("endTime")
public void setEndTime(String endTime) {
this.endTime = endTime;
}
#JsonProperty("exitMessage")
public Object getExitMessage() {
return exitMessage;
}
#JsonProperty("exitMessage")
public void setExitMessage(Object exitMessage) {
this.exitMessage = exitMessage;
}
#JsonProperty("arguments")
public List<String> getArguments() {
return arguments;
}
#JsonProperty("arguments")
public void setArguments(List<String> arguments) {
this.arguments = arguments;
}
#JsonProperty("jobExecutionIds")
public List<Object> getJobExecutionIds() {
return jobExecutionIds;
}
#JsonProperty("jobExecutionIds")
public void setJobExecutionIds(List<Object> jobExecutionIds) {
this.jobExecutionIds = jobExecutionIds;
}
#JsonProperty("errorMessage")
public Object getErrorMessage() {
return errorMessage;
}
#JsonProperty("errorMessage")
public void setErrorMessage(Object errorMessage) {
this.errorMessage = errorMessage;
}
#JsonProperty("externalExecutionId")
public String getExternalExecutionId() {
return externalExecutionId;
}
#JsonProperty("externalExecutionId")
public void setExternalExecutionId(String externalExecutionId) {
this.externalExecutionId = externalExecutionId;
}
#JsonProperty("parentExecutionId")
public Object getParentExecutionId() {
return parentExecutionId;
}
#JsonProperty("parentExecutionId")
public void setParentExecutionId(Object parentExecutionId) {
this.parentExecutionId = parentExecutionId;
}
#JsonProperty("resourceUrl")
public String getResourceUrl() {
return resourceUrl;
}
#JsonProperty("resourceUrl")
public void setResourceUrl(String resourceUrl) {
this.resourceUrl = resourceUrl;
}
#JsonProperty("appProperties")
public AppProperties getAppProperties() {
return appProperties;
}
#JsonProperty("appProperties")
public void setAppProperties(AppProperties appProperties) {
this.appProperties = appProperties;
}
#JsonProperty("deploymentProperties")
public DeploymentProperties getDeploymentProperties() {
return deploymentProperties;
}
#JsonProperty("deploymentProperties")
public void setDeploymentProperties(DeploymentProperties deploymentProperties) {
this.deploymentProperties = deploymentProperties;
}
#JsonProperty("taskExecutionStatus")
public String getTaskExecutionStatus() {
return taskExecutionStatus;
}
#JsonProperty("taskExecutionStatus")
public void setTaskExecutionStatus(String taskExecutionStatus) {
this.taskExecutionStatus = taskExecutionStatus;
}
#JsonProperty("_links")
public Links getLinks() {
return links;
}
#JsonProperty("_links")
public void setLinks(Links links) {
this.links = links;
}
}
Approach 2 : Add spring-cloud-data-flow-rest as a maven dependency in my project and use the TaskExectuionResource entity defined in this project. :
TaskExecutionResource.Page = restTemplate.getForObject("http://dataflow-server.myhost.net/tasks/executions?task1225",
TaskExecutionResource.Page.class);//**Empty content**
Question : How can I deserialize the response of the JSON returned by a rest enndpoint that is using HATEOAS? It seems like a very daunting task to get this to work.
Not sure how you constructed RestTemplate but it doesn't work as is with hateoas and there's some additional steps you need to do.
To get idea what we've done see ObjectMapper config. There's hal module and additional mixin's what mapper needs to be aware of for these things to work.

Incorrectly processing RestTemplate response into object

I'm having some difficulty in parsing a response from a RestTemplate into an instance of a class I've defined.
When I come to process the results, it does give me the correct number of items in the array, but they are all set to default values - it seems unable to process the actual contents from each entry in the response.
This is my class:
public class Authority {
private long localAuthorityId;
private String localAuthorityIdCode;
private String name;
private String friendlyName;
private String url;
private String schemeUrl;
private String email;
private String regionName;
private String fileName;
private String fileNameWelsh;
private int establishmentCount;
private String creationDate;
private String lastPublishedDate;
private int schemeType;
private Link[] links;
public Authority() {}
public Authority (long localAuthorityId, String localAuthorityIdCode, String name, String friendlyName, String url, String schemeUrl,
String email, String regionName, String fileName, String fileNameWelsh, int establishmentCount, String creationDate,
String lastPublishedDate, int schemeType, Link[] links) {
this.localAuthorityId = localAuthorityId;
this.localAuthorityIdCode = localAuthorityIdCode;
this.name = name;
this.friendlyName = friendlyName;
this.url = url;
this.schemeUrl = schemeUrl;
this.email = email;
this.regionName = regionName;
this.fileName = fileName;
this.fileNameWelsh = fileNameWelsh;
this.establishmentCount = establishmentCount;
this.creationDate = creationDate;
this.lastPublishedDate = lastPublishedDate;
this.schemeType = schemeType;
this.links = links;
}
public long getLocalAuthorityId() {
return this.localAuthorityId;
}
public String getLocalAuthorityIdCode() {
return this.localAuthorityIdCode;
}
public String getName() {
return this.name;
}
public String getFriendlyName() {
return this.friendlyName;
}
public String getUrl() {
return this.url;
}
public String getSchemeUrl() {
return this.schemeUrl;
}
public String getEmail() {
return this.email;
}
public String getRegionName() {
return this.regionName;
}
public String getFilename() {
return this.fileName;
}
public String getFileNameWelsh() {
return this.fileNameWelsh;
}
public int getEstablishmentCount() {
return this.establishmentCount;
}
public String getCreationDate() {
return this.creationDate;
}
public String getLastPublishedDate() {
return this.lastPublishedDate;
}
public int getSchemeType() {
return this.schemeType;
}
public Link[] getLinks() {
return this.links;
}
}
This is my response wrapper (where I've confirmed it only ever calls the empty constructor):
public class MyResponseWrapper {
private Authority[] authorities;
public MyResponseWrapper() {
// this is always being called
}
public MyResponseWrapper(Authority[] authorities) {
this.authorities = authorities;
}
public Authority[] getAuthorities() {
return this.authorities;
}
}
And this is how I'm using the RestTemplate:
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.set("Accept", "application/json");
HttpEntity<String> entity = new HttpEntity<>("parameters", headers);
ResponseEntity<MyResponseWrapper> res = restTemplate.exchange(url, HttpMethod.GET, entity, MyResponseWrapper.class);
Here is the JSON I am attempting to parse (I only need the id and name parameters to be stored in MyClass):
{
"authorities":[
{
"LocalAuthorityId":197,
"LocalAuthorityIdCode":"760",
"Name":"Aberdeen City",
"FriendlyName":"aberdeen-city",
"Url":"http://www.aberdeencity.gov.uk",
"SchemeUrl":"",
"Email":"commercial#aberdeencity.gov.uk",
"RegionName":"Scotland",
"FileName":"http://ratings.food.gov.uk/OpenDataFiles/FHRS760en-GB.xml",
"FileNameWelsh":null,
"EstablishmentCount":1847,
"CreationDate":"2010-08-17T15:30:24.87",
"LastPublishedDate":"2018-02-08T00:35:50.717",
"SchemeType":2,
"links":[
{
"rel":"self",
"href":"http://api.ratings.food.gov.uk/authorities/197"
}
]
},
{
"LocalAuthorityId":198,
"LocalAuthorityIdCode":"761",
"Name":"Aberdeenshire",
"FriendlyName":"aberdeenshire",
"Url":"http://www.aberdeenshire.gov.uk/",
"SchemeUrl":"",
"Email":"environmental#aberdeenshire.gov.uk",
"RegionName":"Scotland",
"FileName":"http://ratings.food.gov.uk/OpenDataFiles/FHRS761en-GB.xml",
"FileNameWelsh":null,
"EstablishmentCount":2102,
"CreationDate":"2010-08-17T15:30:24.87",
"LastPublishedDate":"2018-02-24T00:34:15.547",
"SchemeType":2,
"links":[
{
"rel":"self",
"href":"http://api.ratings.food.gov.uk/authorities/198"
}
]
},
{
"LocalAuthorityId":277,
"LocalAuthorityIdCode":"323",
"Name":"Adur",
"FriendlyName":"adur",
"Url":"http://www.adur-worthing.gov.uk",
"SchemeUrl":"",
"Email":"publichealth.regulation#adur-worthing.gov.uk",
"RegionName":"South East",
"FileName":"http://ratings.food.gov.uk/OpenDataFiles/FHRS323en-GB.xml",
"FileNameWelsh":null,
"EstablishmentCount":417,
"CreationDate":"2010-08-17T15:30:24.87",
"LastPublishedDate":"2018-02-28T00:36:33.987",
"SchemeType":1,
"links":[
{
"rel":"self",
"href":"http://api.ratings.food.gov.uk/authorities/277"
}
]
},
{
"LocalAuthorityId":158,
"LocalAuthorityIdCode":"055",
"Name":"Allerdale",
"FriendlyName":"allerdale",
"Url":"http://www.allerdale.gov.uk",
"SchemeUrl":"",
"Email":"environmental.health#allerdale.gov.uk",
"RegionName":"North West",
"FileName":"http://ratings.food.gov.uk/OpenDataFiles/FHRS055en-GB.xml",
"FileNameWelsh":null,
"EstablishmentCount":1092,
"CreationDate":"2010-08-17T15:30:24.87",
"LastPublishedDate":"2018-02-28T00:33:58.31",
"SchemeType":1,
"links":[
{
"rel":"self",
"href":"http://api.ratings.food.gov.uk/authorities/158"
}
]
},
{
"LocalAuthorityId":48,
"LocalAuthorityIdCode":"062",
"Name":"Amber Valley",
"FriendlyName":"amber-valley",
"Url":"http://www.ambervalley.gov.uk",
"SchemeUrl":"",
"Email":"envhealth#ambervalley.gov.uk",
"RegionName":"East Midlands",
"FileName":"http://ratings.food.gov.uk/OpenDataFiles/FHRS062en-GB.xml",
"FileNameWelsh":null,
"EstablishmentCount":972,
"CreationDate":"2010-08-17T15:30:24.87",
"LastPublishedDate":"2018-02-28T00:34:14.493",
"SchemeType":1,
"links":[
{
"rel":"self",
"href":"http://api.ratings.food.gov.uk/authorities/48"
}
]
},
{
"LocalAuthorityId":334,
"LocalAuthorityIdCode":"551",
"Name":"Anglesey",
"FriendlyName":"anglesey",
"Url":"http://www.ynysmon.gov.uk",
"SchemeUrl":"",
"Email":"iechydyramgylchedd#ynysmon.gov.uk",
"RegionName":"Wales",
"FileName":"http://ratings.food.gov.uk/OpenDataFiles/FHRS551en-GB.xml",
"FileNameWelsh":"http://ratings.food.gov.uk/OpenDataFiles/FHRS551cy-GB.xml",
"EstablishmentCount":703,
"CreationDate":"2010-08-17T15:30:24.87",
"LastPublishedDate":"2018-02-28T00:34:28.853",
"SchemeType":1,
"links":[
{
"rel":"self",
"href":"http://api.ratings.food.gov.uk/authorities/334"
}
]
}
],
"meta":{
"dataSource":"API",
"extractDate":"2018-02-28T00:58:26.2673908+00:00",
"itemCount":6,
"returncode":"OK",
"totalCount":6,
"totalPages":1,
"pageSize":6,
"pageNumber":1
},
"links":[
{
"rel":"self",
"href":"http://api.ratings.food.gov.uk/authorities"
},
{
"rel":"first",
"href":"http://api.ratings.food.gov.uk/authorities/1/6"
},
{
"rel":"previous",
"href":"http://api.ratings.food.gov.uk/authorities/1/6"
},
{
"rel":"next",
"href":"http://api.ratings.food.gov.uk/authorities/1/6"
},
{
"rel":"last",
"href":"http://api.ratings.food.gov.uk/authorities/1/6"
}
]
}
I know I'm making a really basic mistake in attempting to parse this response. Would really appreciate if someone could point it out. Cheers.

Json String to Java Object with dynamic key name

I'm trying to parse this structured of json string to Java Object but I failed every attempt.
{
"message": "Test Message",
"status": true,
"users": {
"user_xy": [
{
"time": "2016-08-25 19:01:20.944614158 +0300 EEST",
"age": 24,
"props": {
"pr1": 197,
"pr2": 0.75,
"pr3": 0.14,
"pr4": -0.97
}
}
],
"user_zt": [
{
"time": "2016-08-25 17:08:36.920891187 +0300 EEST",
"age": 29,
"props": {
"pr1": 1.2332131860505051,
"pr2": -0.6628148829634317,
"pr3": -0.11622442112006928
}
}
]
}
}
props field can contain 1 properties or 6 properties, it depends on db record. Also Username part dynamically changing.
Can I parse successfully this structured string with Jackson Lib?
You have to create calss structure like bellow to map your string to java object.
Create one class for Details
public class Details {
private String message;
private String status;
private Map<String, List<UserDetails>> users = new HashMap<String, List<UserDetails>>();
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Map<String, List<UserDetails>> getUsers() {
return users;
}
public void setUsers(Map<String, List<UserDetails>> users) {
this.users = users;
}
}
Create UserDetails class like bellow.
public class UserDetails {
private String time;
private String age;
private Map<String, String> prop = new HashMap<String, String>();
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public Map<String, String> getProp() {
return prop;
}
public void setProp(Map<String, String> prop) {
this.prop = prop;
}
}
Now you can map your string with Details class.
Hope this will help..
public class Details {
private String message;
private boolean status;
Users UsersObject;
// Getter Methods
public String getMessage() {
return message;
}
public boolean getStatus() {
return status;
}
public Users getUsers() {
return UsersObject;
}
// Setter Methods
public void setMessage(String message) {
this.message = message;
}
public void setStatus(boolean status) {
this.status = status;
}
public void setUsers(Users usersObject) {
this.UsersObject = usersObject;
}
}
public class Users {
ArrayList < Object > user_xy = new ArrayList < Object > ();
ArrayList < Object > user_zt = new ArrayList < Object > ();
// Getter Methods
// Setter Methods
}
You can also use online JSON to JAVA Object Converter : https://codebeautify.org/json-to-java-converter

Storing JSON object using Volley

This is the structure of the JSON I need to Load,
{
"readme_0" : "THIS JSON IS THE RESULT OF YOUR SEARCH QUERY - THERE IS NO WEB PAGE WHICH SHOWS THE RESULT!",
"readme_1" : "loklak.org is the framework for a message search system, not the portal, read: http://loklak.org/about.html#notasearchportal",
"readme_2" : "This is supposed to be the back-end of a search portal. For the api, see http://loklak.org/api.html",
"readme_3" : "Parameters q=(query), source=(cache|backend|twitter|all), callback=p for jsonp, maximumRecords=(message count), minified=(true|false)",
"search_metadata" : {
"itemsPerPage" : "100",
"count" : "100",
"count_twitter_all" : 0,
"count_twitter_new" : 100,
"count_backend" : 0,
"count_cache" : 78780,
"hits" : 78780,
"period" : 3066,
"query" : "apple",
"client" : "180.215.121.78",
"time" : 5219,
"servicereduction" : "false",
"scraperInfo" : "http://45.55.245.191:9000,local"
},
"statuses" : [ {
"created_at" : "2016-01-09T12:11:38.000Z",
"screen_name" : "arifazmi92",
"text" : "Perhaps I shouldn't have eaten that pisang goreng cheese perisa green apple. <img class=\"Emoji Emoji--forText\" src=\"https://abs.twimg.com/emoji/v2/72x72/1f605.png\" draggable=\"false\" alt=\"😅\" title=\"Smiling face with open mouth and cold sweat\" aria-label=\"Emoji: Smiling face with open mouth and cold sweat\"><img class=\"Emoji Emoji--forText\" src=\"https://abs.twimg.com/emoji/v2/72x72/1f605.png\" draggable=\"false\" alt=\"😅\" title=\"Smiling face with open mouth and cold sweat\" aria-label=\"Emoji: Smiling face with open mouth and cold sweat\"><img class=\"Emoji Emoji--forText\" src=\"https://abs.twimg.com/emoji/v2/72x72/1f605.png\" draggable=\"false\" alt=\"😅\" title=\"Smiling face with open mouth and cold sweat\" aria-label=\"Emoji: Smiling face with open mouth and cold sweat\">",
"link" : "https://twitter.com/arifazmi92/status/685796067082813440",
"id_str" : "685796067082813440",
"source_type" : "TWITTER",
"provider_type" : "SCRAPED",
"retweet_count" : 0,
"favourites_count" : 0,
"images" : [ ],
"images_count" : 0,
"audio" : [ ],
"audio_count" : 0,
"videos" : [ ],
"videos_count" : 0,
"place_name" : "Bandar Shah Alam, Selangor",
"place_id" : "9be3b0eca6c21f6c",
"place_context" : "FROM",
"place_country" : "Malaysia",
"place_country_code" : "MY",
"place_country_center" : [ -59.30559537806809, 3.4418498787292435 ],
"location_point" : [ 101.53280621465888, 3.0850698533863863 ],
"location_radius" : 0,
"location_mark" : [ 101.52542227271437, 3.0911033774188725 ],
"location_source" : "PLACE",
"hosts" : [ "abs.twimg.com" ],
"hosts_count" : 1,
"links" : [ "https://abs.twimg.com/emoji/v2/72x72/1f605.png\"", "https://abs.twimg.com/emoji/v2/72x72/1f605.png\"", "https://abs.twimg.com/emoji/v2/72x72/1f605.png\"" ],
"links_count" : 3,
"mentions" : [ ],
"mentions_count" : 0,
"hashtags" : [ ],
"hashtags_count" : 0,
"without_l_len" : 626,
"without_lu_len" : 626,
"without_luh_len" : 626,
"user" : {
"screen_name" : "arifazmi92",
"user_id" : "44503967",
"name" : "Arif Azmi",
"profile_image_url_https" : "https://pbs.twimg.com/profile_images/685788990004301824/NbFnnLuO_bigger.jpg",
"appearance_first" : "2016-01-09T12:11:57.933Z",
"appearance_latest" : "2016-01-09T12:11:57.933Z"
}
}
} ],
"aggregations" : { }
}
And these are my POJO classes that I've generated:
MainPojo.class
public class MainPojo
{
#SerializedName("readme_0")
#Expose
private String readme0;
#SerializedName("readme_1")
#Expose
private String readme1;
#SerializedName("readme_2")
#Expose
private String readme2;
#SerializedName("readme_3")
#Expose
private String readme3;
#SerializedName("search_metadata")
#Expose
private SearchMetadata searchMetadata;
#SerializedName("statuses")
#Expose
private List<Status> statuses = new ArrayList<Status>();
#SerializedName("aggregations")
#Expose
private Aggregations aggregations;
public String getReadme0() {
return readme0;
}
public void setReadme0(String readme0) {
this.readme0 = readme0;
}
public String getReadme1() {
return readme1;
}
public void setReadme1(String readme1) {
this.readme1 = readme1;
}
public String getReadme2() {
return readme2;
}
public void setReadme2(String readme2) {
this.readme2 = readme2;
}
public String getReadme3() {
return readme3;
}
public void setReadme3(String readme3) {
this.readme3 = readme3;
}
public SearchMetadata getSearchMetadata() {
return searchMetadata;
}
public void setSearchMetadata(SearchMetadata searchMetadata) {
this.searchMetadata = searchMetadata;
}
public List<Status> getStatuses() {
return statuses;
}
public void setStatuses(List<Status> statuses) {
this.statuses = statuses;
}
public Aggregations getAggregations() {
return aggregations;
}
public void setAggregations(Aggregations aggregations) {
this.aggregations = aggregations;
}
}
Status.class
public class Status
{
#SerializedName("created_at")
#Expose
private String createdAt;
#SerializedName("screen_name")
#Expose
private String screenName;
#SerializedName("text")
#Expose
private String text;
#SerializedName("link")
#Expose
private String link;
#SerializedName("id_str")
#Expose
private String idStr;
#SerializedName("source_type")
#Expose
private String sourceType;
#SerializedName("provider_type")
#Expose
private String providerType;
#SerializedName("retweet_count")
#Expose
private Integer retweetCount;
#SerializedName("favourites_count")
#Expose
private Integer favouritesCount;
#SerializedName("images")
#Expose
private List<Object> images = new ArrayList<Object>();
#SerializedName("images_count")
#Expose
private Integer imagesCount;
#SerializedName("audio")
#Expose
private List<Object> audio = new ArrayList<Object>();
#SerializedName("audio_count")
#Expose
private Integer audioCount;
#SerializedName("videos")
#Expose
private List<Object> videos = new ArrayList<Object>();
#SerializedName("videos_count")
#Expose
private Integer videosCount;
#SerializedName("place_name")
#Expose
private String placeName;
#SerializedName("place_id")
#Expose
private String placeId;
#SerializedName("place_context")
#Expose
private String placeContext;
#SerializedName("location_point")
#Expose
private List<Double> locationPoint = new ArrayList<Double>();
#SerializedName("location_radius")
#Expose
private Integer locationRadius;
#SerializedName("location_mark")
#Expose
private List<Double> locationMark = new ArrayList<Double>();
#SerializedName("location_source")
#Expose
private String locationSource;
#SerializedName("hosts")
#Expose
private List<String> hosts = new ArrayList<String>();
#SerializedName("hosts_count")
#Expose
private Integer hostsCount;
#SerializedName("links")
#Expose
private List<String> links = new ArrayList<String>();
#SerializedName("links_count")
#Expose
private Integer linksCount;
#SerializedName("mentions")
#Expose
private List<Object> mentions = new ArrayList<Object>();
#SerializedName("mentions_count")
#Expose
private Integer mentionsCount;
#SerializedName("hashtags")
#Expose
private List<Object> hashtags = new ArrayList<Object>();
#SerializedName("hashtags_count")
#Expose
private Integer hashtagsCount;
#SerializedName("without_l_len")
#Expose
private Integer withoutLLen;
#SerializedName("without_lu_len")
#Expose
private Integer withoutLuLen;
#SerializedName("without_luh_len")
#Expose
private Integer withoutLuhLen;
#SerializedName("user")
#Expose
private User user;
#SerializedName("provider_hash")
#Expose
private String providerHash;
#SerializedName("classifier_language")
#Expose
private String classifierLanguage;
#SerializedName("classifier_language_probability")
#Expose
private Double classifierLanguageProbability;
public String getCreatedAt() {
return createdAt;
}
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
public String getScreenName() {
return screenName;
}
public void setScreenName(String screenName) {
this.screenName = screenName;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getIdStr() {
return idStr;
}
public void setIdStr(String idStr) {
this.idStr = idStr;
}
public String getSourceType() {
return sourceType;
}
public void setSourceType(String sourceType) {
this.sourceType = sourceType;
}
public String getProviderType() {
return providerType;
}
public void setProviderType(String providerType) {
this.providerType = providerType;
}
public Integer getRetweetCount() {
return retweetCount;
}
public void setRetweetCount(Integer retweetCount) {
this.retweetCount = retweetCount;
}
public Integer getFavouritesCount() {
return favouritesCount;
}
public void setFavouritesCount(Integer favouritesCount) {
this.favouritesCount = favouritesCount;
}
public List<Object> getImages() {
return images;
}
public void setImages(List<Object> images) {
this.images = images;
}
public Integer getImagesCount() {
return imagesCount;
}
public void setImagesCount(Integer imagesCount) {
this.imagesCount = imagesCount;
}
public List<Object> getAudio() {
return audio;
}
public void setAudio(List<Object> audio) {
this.audio = audio;
}
public Integer getAudioCount() {
return audioCount;
}
public void setAudioCount(Integer audioCount) {
this.audioCount = audioCount;
}
public List<Object> getVideos() {
return videos;
}
public void setVideos(List<Object> videos) {
this.videos = videos;
}
public Integer getVideosCount() {
return videosCount;
}
public void setVideosCount(Integer videosCount) {
this.videosCount = videosCount;
}
public String getPlaceName() {
return placeName;
}
public void setPlaceName(String placeName) {
this.placeName = placeName;
}
public String getPlaceId() {
return placeId;
}
public void setPlaceId(String placeId) {
this.placeId = placeId;
}
public String getPlaceContext() {
return placeContext;
}
public void setPlaceContext(String placeContext) {
this.placeContext = placeContext;
}
public List<Double> getLocationPoint() {
return locationPoint;
}
public void setLocationPoint(List<Double> locationPoint) {
this.locationPoint = locationPoint;
}
public Integer getLocationRadius() {
return locationRadius;
}
public void setLocationRadius(Integer locationRadius) {
this.locationRadius = locationRadius;
}
public List<Double> getLocationMark() {
return locationMark;
}
public void setLocationMark(List<Double> locationMark) {
this.locationMark = locationMark;
}
public String getLocationSource() {
return locationSource;
}
public void setLocationSource(String locationSource) {
this.locationSource = locationSource;
}
public List<String> getHosts() {
return hosts;
}
public void setHosts(List<String> hosts) {
this.hosts = hosts;
}
public Integer getHostsCount() {
return hostsCount;
}
public void setHostsCount(Integer hostsCount) {
this.hostsCount = hostsCount;
}
public List<String> getLinks() {
return links;
}
public void setLinks(List<String> links) {
this.links = links;
}
public Integer getLinksCount() {
return linksCount;
}
public void setLinksCount(Integer linksCount) {
this.linksCount = linksCount;
}
public List<Object> getMentions() {
return mentions;
}
public void setMentions(List<Object> mentions) {
this.mentions = mentions;
}
public Integer getMentionsCount() {
return mentionsCount;
}
public void setMentionsCount(Integer mentionsCount) {
this.mentionsCount = mentionsCount;
}
public List<Object> getHashtags() {
return hashtags;
}
public void setHashtags(List<Object> hashtags) {
this.hashtags = hashtags;
}
public Integer getHashtagsCount() {
return hashtagsCount;
}
public void setHashtagsCount(Integer hashtagsCount) {
this.hashtagsCount = hashtagsCount;
}
public Integer getWithoutLLen() {
return withoutLLen;
}
public void setWithoutLLen(Integer withoutLLen) {
this.withoutLLen = withoutLLen;
}
public Integer getWithoutLuLen() {
return withoutLuLen;
}
public void setWithoutLuLen(Integer withoutLuLen) {
this.withoutLuLen = withoutLuLen;
}
public Integer getWithoutLuhLen() {
return withoutLuhLen;
}
public void setWithoutLuhLen(Integer withoutLuhLen) {
this.withoutLuhLen = withoutLuhLen;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getProviderHash() {
return providerHash;
}
public void setProviderHash(String providerHash) {
this.providerHash = providerHash;
}
public String getClassifierLanguage() {
return classifierLanguage;
}
public void setClassifierLanguage(String classifierLanguage) {
this.classifierLanguage = classifierLanguage;
}
public Double getClassifierLanguageProbability() {
return classifierLanguageProbability;
}
public void setClassifierLanguageProbability(Double classifierLanguageProbability) {
this.classifierLanguageProbability = classifierLanguageProbability;
}
}
User.java
public class User {
#SerializedName("screen_name")
#Expose
private String screenName;
#SerializedName("user_id")
#Expose
private String userId;
#SerializedName("name")
#Expose
private String name;
#SerializedName("profile_image_url_https")
#Expose
private String profileImageUrlHttps;
#SerializedName("appearance_first")
#Expose
private String appearanceFirst;
#SerializedName("appearance_latest")
#Expose
private String appearanceLatest;
public String getScreenName() {
return screenName;
}
public void setScreenName(String screenName) {
this.screenName = screenName;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getProfileImageUrlHttps() {
return profileImageUrlHttps;
}
public void setProfileImageUrlHttps(String profileImageUrlHttps) {
this.profileImageUrlHttps = profileImageUrlHttps;
}
public String getAppearanceFirst() {
return appearanceFirst;
}
public void setAppearanceFirst(String appearanceFirst) {
this.appearanceFirst = appearanceFirst;
}
public String getAppearanceLatest() {
return appearanceLatest;
}
public void setAppearanceLatest(String appearanceLatest) {
this.appearanceLatest = appearanceLatest;
}
}
Aggregations.class
public class Aggregations {
}
And finally, this is the code I use to read the JSON and store as JSON objects,
SharedPreferences Tempx = getSharedPreferences("ActivitySession", Context.MODE_PRIVATE);
SharedPreferences.Editor edx = Tempx.edit();
edx.putString("GSON_FEED", response.toString());
edx.apply();
Gson gson = new Gson();
JsonParser parser = new JsonParser();
try{
JsonArray jArray = parser.parse(Tempx.getString("GSON_FEED","")).getAsJsonArray();
for(JsonElement obj : jArray )
{
MainPojo cse = gson.fromJson( obj , MainPojo.class);
TweetList.add(cse);
}
}catch(Throwable e) {
JsonElement obj = parser.parse(Tempx.getString("GSON_FEED","")).getAsJsonObject();
MainPojo cse = gson.fromJson( obj , MainPojo.class);
TweetList.add(cse);
}
Though I am able to log the JSON as String, I don't know if I am storing it the wrong way, any help will be much appreciated, Thanks!
You could define a custom deserializer and register a type adapter with GSON. Also
why are you using this:
JsonArray jArray = parser.parse(Tempx.getString("GSON_FEED","")).getAsJsonArray();
.. when you intend to use GSON for deserialization? You could just do it in your deserializer.
https://sites.google.com/site/gson/gson-user-guide#TOC-Custom-Serialization-and-Deserialization
EG:
public class FooDeserializer implements JsonDeserializer<Foos>
{
#Override public Foos deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException
{
JsonObject jsonObject = json.getAsJsonObject();
JsonArray statusArray = jsonObject.get("statuses").getAsJsonArray();
Foos result = new Foos();
ArrayList fooArray = new ArrayList<>;
for (JsonElement e : statusArray) {
fooArray.add(new Foo());
}
result.setFoos(fooArray);
return result;
}
}

Create json object using java

I have tried several ways to create follwing format json using java. (Gson , Jackson , ...)
{
"outbound": {
"address": [
"t91",
"t0992"
],
"send": "t678",
"outMessage": {
"message": "Hello World"
},
"client": "156",
"receipt": {
"URL": "http://example.com/Delivery",
"callback": "some-to-the-request"
},
"senderName": "Inc."
}
}
Any help?
Use code below.
Create POJO
public class TestPojo {
private Outbound outbound;
public Outbound getOutbound() {
return outbound;
}
public void setOutbound(Outbound outbound) {
this.outbound = outbound;
}
}
class Outbound {
private String[] address;
private String send;
private OutMessage outMessage;
private Receipt receipt;
private String senderName;
public String[] getAddress() {
return address;
}
public void setAddress(String[] address) {
this.address = address;
}
public String getSend() {
return send;
}
public void setSend(String send) {
this.send = send;
}
public OutMessage getOutMessage() {
return outMessage;
}
public void setOutMessage(OutMessage outMessage) {
this.outMessage = outMessage;
}
public Receipt getReceipt() {
return receipt;
}
public void setReceipt(Receipt receipt) {
this.receipt = receipt;
}
public String getSenderName() {
return senderName;
}
public void setSenderName(String senderName) {
this.senderName = senderName;
}
}
class OutMessage {
private String message;
public OutMessage(String message) {
super();
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
class Receipt {
private String URL;
private String callback;
public Receipt(String uRL, String callback) {
super();
URL = uRL;
this.callback = callback;
}
public String getURL() {
return URL;
}
public void setURL(String uRL) {
URL = uRL;
}
public String getCallback() {
return callback;
}
public void setCallback(String callback) {
this.callback = callback;
}
}
Main Class (JSON to Object)
String json = "{'outbound':{'address':['t91','t0992'],'send':'t678','outMessage':{'message':'Hello World'},'receipt':{'URL':'http://example.com/Delivery','callback':'some-to-the-request'},'senderName':'Inc.'}}";
TestPojo testPojo = new Gson().fromJson(json, TestPojo.class);
System.out.println(testPojo.getOutbound().getSenderName());
Output
Inc.
Main Class (Object to JSON)
TestPojo testPojo = new TestPojo();
Outbound outbound = new Outbound();
outbound.setAddress(new String[]{"t91", "t0992"});
outbound.setOutMessage(new OutMessage("Hello World"));
outbound.setReceipt(new Receipt("http://example.com/Delivery", "some-to-the-request"));
outbound.setSenderName("Inc.");
outbound.setSend("t678");
testPojo.setOutbound(outbound);
System.out.println(new Gson().toJson(testPojo));
Output
{"outbound":{"address":["t91","t0992"],"send":"t678","outMessage":{"message":"Hello World"},"receipt":{"URL":"http://example.com/Delivery","callback":"some-to-the-request"},"senderName":"Inc."}}
Detail
Used GSON library.
Used a json given by you.

Categories