I need to build a below JSON programmatically. But,need a elegant way to convert from Java object to JSON. so that, i can avoid string builder to build the below JSON.
I aware of that, sometimes,I have array of parameters for the specific key while building JSON.
Please share the generic way to solve that.
Please share some thoughts to this.
{
"tropo": [
{
"ask": {
"attempts": 3,
"say": [
{
"value": "Hi.",
"event": "timeout"
},
{
"value": "Hello",
"event": "nomatch:1"
},
{
"value": "Hello2",
"event": "nomatch:2"
},
{
"value": "Satheesh",
"voice": "veronica"
}
],
"choices": {
"value": "Yes(1,Yes),No(2,No)",
"mode": "ANY"
},
"voice": "veronica",
"recognizer": "en-us",
"timeout": 8,
"name": "year",
"minConfidence": 39,
"required": true
}
},
{
"on": {
"next": "https://test.app.com/WAP2/",
"event": "continue"
}
},
{
"on": {
"next": "https://test.app.com/WAP2/",
"event": "incomplete"
}
},
{
"on": {
"next": "",
"event": "hangup"
}
}
]
}
As paulsm4 said, I'd have a look at gson. It's easy to use, you can find a lot of example of how it works all over the web (official user guide).
Example:
Employee employee = new Employee();
employee.setId(1);
employee.setFirstName("Lokesh");
employee.setLastName("Gupta");
employee.setRoles(Arrays.asList("ADMIN", "MANAGER"));
Gson gson = new Gson();
System.out.println(gson.toJson(employee));
Output:
{"id":1,"firstName":"Lokesh","lastName":"Gupta","roles":["ADMIN","MANAGER"]}
From howtodoinjava.com/'s Google Gson Tutorial : Convert Java Object to / from JSON.
Related
I'm having difficulty implementing a JSON to send as a POST call in Spring.
Which is the fastest and most effective way to turn this json into a java object or a map and make the call?
below is an example of a json to send:
{
"apiVersion": "apps/v1",
"kind": "Deployment",
"metadata": {
"name": "edge-ws"
},
"spec": {
"selector": {
"matchLabels": {
"run": "edge-ws"
}
},
"replicas": 1,
"template": {
"metadata": {
"labels": {
"run": "edge-ws"
}
},
"spec": {
"containers": [
{
"name": "edge-ws",
"image": "server-tim:latest",
"imagePullPolicy": "Never",
"ports": [
{
"containerPort": 80
}
]
}
]
}
}
}
}
this and the second body that has a value (nodeport) that must be taken from a field entered by the user front end side.(page created in html)
{
"apiVersion": "v1",
"kind": "Service",
"metadata": {
"name": "edge-ws",
"labels": {
"run": "edge-ws"
}
},
"spec": {
"type": "NodePort",
"ports": [
{
"port": 8080,
"targetPort": 80,
"nodePort": 30200,
"protocol": "TCP",
"name": "http"
}
],
"selector": {
"run": "edge-ws"
}
}
}
Both files must be sent with a single click on a button on the front end side.the first call with the first body starts and if everything is ok the second body starts
What should the class that maps objects look like? What should the controller look like instead?
They also gave me an address to call that can only be used on the machine, how can I test this call locally?
Thanks in advance!
You can use google's Gson library to convert the JsonString to Object and then use below code:
Gson gson = new Gson();
Object requestObject = gson.fromJson(jsonString, Object.class);
ResponseObject responseObject = restTemplate.postForObject(url, requestObject, ResponseObject.class);
I'm trying to flatten the below response without having to parse it into a class. The reason for this is that the server could add or remove fields at anytime so it needs to be dynamic. We also have another service that returns lookup paths that we use to get data out of the flattened response - like "$.detail.att_one" There is a library for iOS that does the exact thing I'm looking for but as far as I can find nothing similar for Android: https://github.com/infinum/Japx
{
"data": [
{
"type": "items",
"id": "14",
"attributes": {
"item_type": "shape_circle",
"code": null,
"size": "70"
},
"relationships": {
"detail": {
"data": {
"type": "circle",
"id": "90"
}
},
"metadata": {
"data": "metadata"
}
},
"links": {
"self": "http://url/item/14"
}
}
],
"included": [
{
"type": "circle",
"id": "90",
"attributes": {
"att_one": 4,
"att_two": "11111111111",
"att_three": "Bob"
}
}
]}
The result I'm looking for:
{
"data": [
{
"id": "14",
"type": "items",
"item_type": "shape_circle",
"code": null,
"size": "70",
"metadata": {
"data": "metadata"
},
"detail": {
"type": "circle",
"id": "90",
"att_one": 4,
"att_two": "11111111111",
"att_three": "Bob"
},
"links": {
"self": "http://url/item/14"
}
}
]}
There is a nice JSONAPI library that does the thing, but you have to define resource classes for it.
Check out jasminb/jsonapi-converter
It recursively flattens all the included relationships and handles inheritance.
I have the following JSON object:
{
"_class": "hudson.model.FreeStyleBuild",
"actions": [
{
"_class": "hudson.model.CauseAction",
"causes": [
{
"_class": "hudson.model.Cause$UserIdCause",
"shortDescription": "Started by user SYSTEM",
"userId": "SYSTEM",
"userName": "SYSTEM"
},
{
"_class": "hudson.model.Cause$UserIdCause",
"shortDescription": "Started by user SYSTEM",
"userId": "SYSTEM",
"userName": "SYSTEM"
},
{
"_class": "hudson.model.Cause$UserIdCause",
"shortDescription": "Started by user SYSTEM",
"userId": "SYSTEM",
"userName": "SYSTEM"
},
{
"_class": "com.sonyericsson.rebuild.RebuildCause",
"shortDescription": "Rebuilds build #1",
"upstreamBuild": 1,
"upstreamProject": "gcimpoies-test5",
"upstreamUrl": "job/gcimpoies-test5/"
},
{
"_class": "com.sonyericsson.rebuild.RebuildCause",
"shortDescription": "Rebuilds build #1",
"upstreamBuild": 1,
"upstreamProject": "gcimpoies-test5",
"upstreamUrl": "job/gcimpoies-test5/"
}
]
},
{
"_class": "hudson.model.CauseAction",
"causes": [
{
"_class": "com.sonyericsson.rebuild.RebuildCause",
"shortDescription": "Rebuilds build #1",
"upstreamBuild": 1,
"upstreamProject": "gcimpoies-test5",
"upstreamUrl": "job/gcimpoies-test5/"
}
]
},
{
},
{
"_class": "com.sonyericsson.jenkins.plugins.bfa.model.FailureCauseBuildAction"
},
{
},
{
},
{
}
],
"artifacts": [
],
"building": false,
"description": null,
"displayName": "#2",
"duration": 15,
"estimatedDuration": 61,
"executor": null,
"fullDisplayName": "gcimpoies-test5 #2",
"id": "2",
"keepLog": false,
"number": 2,
"queueId": 6,
"result": "FAILURE",
"timestamp": 1522153325922,
"url": "http://localhost:8080/job/gcimpoies-test5/2/",
"builtOn": "",
"changeSet": {
"_class": "hudson.scm.EmptyChangeLogSet",
"items": [
],
"kind": null
},
"culprits": [
]
}
And I want to extract the username: SYSTEM
I tried using JsonSlurper but with no luck. I believe the right way to go is using JSONObject instead.
Any help is much appreciated.
You can use Google Gson for parsing json in java. Here I am pasting the code to convert json into Map. So that you can simply access json as map object.
Map map = gson.fromJson(jsonString, Map.class);
System.out.println(map);
For more info, please read this thread.
Gson gson = new Gson();
Map buildDetailsMap;
buildDetailsMap = gson.fromJson(json, Map.class);
if (buildDetailsMap != null) {
List actions = (List) buildDetailsMap.get("actions");
Map actionZero = (Map) actions.get(0);
List causes = (List) actionZero.get("causes");
Map causeZero = (Map) causes.get(0);
username = (String) causeZero.get("userName");
}
This is how I did it. Thanks SV Madhava Revy
{
"code": 200,
"message": "Success",
"data": [
{
"holidayId": 1,
"createdAt": 1334925720000,
"date": "2012-01-26",
"description": "Republic Day",
"holidayType": {
"holidayTypeId": 1,
"holidayType": "Normal"
}
},
{
"holidayId": 11,
"createdAt": 1334925720000,
"date": "2012-03-23",
"description": "Ugadi",
"holidayType": {
"holidayTypeId": 2,
"holidayType": "Normal"
}
},
{
"holidayId": 21,
"createdAt": 1334925720000,
"date": "2012-04-06",
"description": "Good Friday",
"holidayType": {
"holidayTypeId": 1,
"holidayType": "Normal"
}
},
{
"holidayId": 31,
"createdAt": 1334925720000,
"date": "2012-05-01",
"description": "May Day",
"holidayType": {
"holidayTypeId": 2,
"holidayType": "Normal"
}
},
}
]
}
this is my Current JSON format:
public CommonResponseModel getLeaveList() {
EntityManager entityManager = DBManager.getDBManager();
List<Holiday> result = entityManager.createQuery("FROM Holiday", Holiday.class).getResultList();
LeavesResponseWrapper model = new LeavesResponseWrapper();
model.setData(result);
DBManager.saveAndClosDB(entityManager);
return model;
}
this code i am trying to get current JSON data
But i have to get JSON Data in this format desire format:
{
"code": 200,
"message": "Holiday List",
"data": {
"normalHolidays": [
{
"name": "Diwali",
"date": "31-10-2016"
}
],
"optionalHolidays": [
{
"name": "Onam",
"date": "13-09-2016"
}
]
}
}
please help me how to achieve desire JSON format data we have two table one for holidays and another for Holidays type on the basis of that i am getting that data while i have to get To json array one for TYPE1 another for type2 i am using Jersey jar please help me how to get it .
Change the type of "data" from List<Holiday> to Map<String,List<Holiday>>.
Then based on holidayType you can separate data in setData().
Map<String,List<Holiday>> data;
setData(List<Holiday> holidays) {
List<Holiday> normalHolidays = new ArrayList<Holiday>();
List<Holiday> optionalHolidays = new ArrayList<Holiday>();
for(Holiday holiday : holidays) {
if("Normal".equals(holiday.holidayType.holidayType)) {
normalHolidays.add(holiday);
} else {
optionalHolidays.add(holiday);
}
}
data = new HashMap<String,List<Holiday>>();
data.put("normalHolidays", normalHolidays);
data.put("optionalHolidays", optionalHolidays);
}
How can i convert jira json string to java object i want to get the issue details
{
"expand": "schema,names",
"startAt": 0,
"maxResults": 50,
"total": 1,
"issues": [
{
"expand": "editmeta,renderedFields,transitions,changelog,operations",
"id": "10000",
"self": "http://jira.com/rest/api/2/issue/10000",
"key": "APPANLYTIX-1",
"fields": {},
"issuetype": {},
"votes": {},
"resolution": null,
"fixVersions": [{}],
"resolutiondate": null,
"timespent": null,
"reporter": {
"avatarUrls": {},
"displayName": "yyyy Dev",
"active": true
},
"subtasks": [],
"status": {},
"labels": [],
"workratio": 0,
"assignee": {
"avatarUrls": {},
"displayName": "",
"active": true
},
"project": {
"name": "",
"avatarUrls": { }
},
"versions": [{}],
"environment": "windows",
"timeestimate": 28800,
"aggregateprogress": {},
"lastViewed": "2013-07-18T04:39:52.596+0000",
"components": [ ],
"timeoriginalestimate": 28800,
"aggregatetimespent": null
}
]
}
Most of the examples I refereed are using java bean for setting the variables,is there any API for doing this?
If your class has a structure like the json you've showed you can use use the gson library to bind it to the class.
I handle this problem another third party library, you can download this code. And Edit as your scenario.
You should only edit SimpleConfigurationProvider this java class.
You have to specify your privateKey, AccessToken and baseUrl. And then jiraClient Authentication you can receive project and issue thanks to under code block
As a result you can convert java class object as ArrayList and JiraProject[]
https://github.com/symphonyoss/bot-jira
public static void main(String[] args) {
// TODO Auto-generated method stub
JiraOauthClient jiraClient = new JiraOauthClient(new SimpleConfigurationProvider());
JiraProject[] projects = jiraClient.getAllProjects();
for (JiraProject project : projects) {
if (project.getKey().equals("UOCM")) {
ArrayList<JiraIssue> issues = jiraClient.getIssuesForProject(project);
for (JiraIssue issue : issues) {
System.out.println(issue.getId());
///.....
}
}
}
}