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);
Related
I have a JSON file like this:
{
"Resources": {
"HelloWorldFunction": {
"Type": "AWS::Serverless::Function",
"Properties": {
"Handler": "index.handler",
"Runtime": "nodejs8.10",
"Events": {
"HelloWorldApi": {
"Type": "Api",
"Properties": {
"Path": "/",
"Method": "GET"
}
}
},
"Policies": [
{
"SNSPublishMessagePolicy": {
"TopicName": {
"Fn::GetAtt": [
"HelloWorldTopic",
"TopicName"
]
}
}
}
],
"Environment": {
"Variables": {
"SNS_TOPIC_ARN": {
"Ref": "HelloWorldTopic"
}
}
},
"CodeUri": "nothing"
}
},
"HelloWorldTopic": {
"Type": "AWS::SNS::Topic",
"Properties": {
"Subscription": [
{
"Endpoint": "nothing",
"Protocol": "email"
}
]
}
}
}
}
I am using the Jackson YAMLFactory to parse a YAML-file that is equivalent to this JSON. How can I parse this in a way that all the content inside "Resources" is stored in a single String? (I want to keep this as a separate YAML/JSON for further analysis)
ObjectMapper mapper = new ObjectMapper();
String resources = mapper.readTree(new FileReader(path_to_your_json_file).at("/Resources").asText()
Or something like this.
I am not able to get a list of id from the below json with the help of RestAssured JsonPath.
{
"Test": [
{
"id": "657"
},
{
"id": "2711"
}
],
"Test2": [
{
"id": "657"
},
{
"id": "711"
}
]
}
I have a json such as below
{
"apiVersion": "v1",
"metadata": {
"status": {
"statusCode": 0
},
},
"stuff": [
{
"name": {
"text": "red"
},
"properties": [
{
"attributes": {
"shade": "dark"
},
"component": {
"id": "BA1",
}
"type": "Color"
}
]
},
{
"name": {
"text": "Toyota Camry"
},
"properties": [
{
"attributes": {},
"component": {
"id": "MS",
},
"type": "Vehicle"
}
]
},
]
}
I'm using GSON to parse the results like this:
Gson gson = new Gson();
JsonObject json = (JsonObject) gson.fromJson(in, JsonObject.class);
System.out.println(json.get("apiVersion").getAsString());
I can get the apiVersion but don't know how to get elements that are inside the json tree. For example, type...what if I want to output all the different type..in this case Color and Vehicle
I must be missing something here, but why can't you nest calls to getJsonObject? For example, to get the status code:
System.out.println(json.getAsJsonObject("metadata")
.getAsJsonObject("status")
.get("statusCode").getAsInt());
You can create an object in that matter and to parse the json to it (with GSON):
ParsedObject parsedObject = new Gson().fromJson(json, ParsedObject.class);
public class ParsedObject {
#SerializedName(value = "apiVersion")
private String mApiVersion;
#SerializedName(value = "metadata")
private Metadata mMetadata;
}
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.
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());
///.....
}
}
}
}