How to use variable in .json file and change it in java - java

I have a .json file and i read it to use Files.readAllBytes(Paths.get("classpath")). It works but i need to use variable in .json file and i just want to change variable in other method.
Here is my .json file:
{
"type": "FILE",
"invitationMessage": "",
"duration": "NO_EXPIRE",
"items": [
{
"uuid": "shdy28-9b03-4c21-9c80-f96f31f9cee9",
"projectId": "65ht8f99694454a658yef17a95e8f"
}
],
"invitees": [
{
"username": "variable#gmail.com",
"role": "VIEWER"
}
]
}
This is the method I used the file:
#When("^I send share privately api$")
public void sharePrivately() throws IOException {
String body = new String(Files.readAllBytes(Paths.get("src/test/resources/config/environments/sharePrivately.json")));
RequestSpecification header = rh.share(payload.userAuth());
response = header.body(body)
.when()
.post("/shares")
.then()
.assertThat()
.extract()
.response();
System.out.println(response.getStatusCode());
}
When i read .json file i want to change username in this method. How can do that ?
Thank you for your advice

Your user name is stored in invitees Array so you need to replace that. For that, we can use JSONObject like below,
String body = new String(Files
.readAllBytes(Paths.get("src/test/resources/config/environments/sharePrivately.json")));
JSONObject jsonObject = new JSONObject(body);
jsonObject.put("invitees", new JSONArray("[{\"username\": \"Nandan#gmail.com\",\"role\": \"VIEWER\"}]"));
In your code,
response = header.body(jsonObject.toString())
.when()
.post("/shares")
.then()
.assertThat()
.extract()
.response();
Output:
{
"duration": "NO_EXPIRE",
"invitees": [
{
"role": "VIEWER",
"username": "Nandan#gmail.com"
}
],
"invitationMessage": "",
"type": "FILE",
"items": [
{
"uuid": "shdy28-9b03-4c21-9c80-f96f31f9cee9",
"projectId": "65ht8f99694454a658yef17a95e8f"
}
]
}
You need to use below import,
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160212</version>
</dependency>

Related

Java - JSON to YAML (Dynamic) [duplicate]

This question already has answers here:
Convert JSON to YAML. Parsing JSON to YAML
(7 answers)
Closed 2 years ago.
I want to convert JSON to YAML. And I want to this in Java dynamically. Based on the componentId, properties will change. This JSON can vary and supports multiple componentIds and this comes from HTTP request.
Example JSON:
[
{
"id": "timer",
"attributes": {
"type": "tick"
"period": "5000"
},
"output": "transform"
},
{
"id": "transform",
"attributes": {
"expression": "${body.toUpperCase()}”,
“type”: “simple"
},
"output": "log"
},
{
"id": "log",
"attributes": {
"message": "hello world”,
“type”: “info"
}
}
]
Expected YAML:
- from:
uri: "timer:tick"
parameters:
period: "5000"
steps:
- set-body:
constant: "Hello Yaml!!!"
- transform:
simple: "${body.toUpperCase()}"
- to: "log:info”
I think you should be able to convert any kind of JSON to YAML using Jackson. Add the following dependencies to your project:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
<version>${jackson.version}</version>
</dependency>
If you have an input Kamelet JSON string like this:
{
"apiVersion": "camel.apache.org/v1alpha1",
"kind": "Kamelet",
"metadata": {
"name": "echo-sink",
"labels": {
"camel.apache.org/kamelet.type": "sink"
}
},
"spec": {
"definition": {
"title": "Echo",
"description": "Replies with an echo message to each incoming event",
"properties": {
"prefix": {
"title": "Prefix",
"description": "The prefix to prepend to the incoming event",
"type": "string",
"default": "echo: "
}
}
},
"types": {
"in": {
"mediaType": "text/plain"
},
"out": {
"mediaType": "text/plain"
}
},
"flow": {
"from": {
"uri": "kamelet:source",
"steps": [
{
"set-body": {
"simple": "{{prefix}}${body}"
}
}
]
}
}
}
}
You can easily convert it into YAML using Jackson like this:
File jsonFile = new File(JsonToYaml.class.getResource("/kamelet.json").getFile());
ObjectMapper jsonMapper = new ObjectMapper();
YAMLMapper yamlMapper = new YAMLMapper();
// Read file as JsonNode
JsonNode jsonNode = jsonMapper.readTree(jsonFile);
// Convert it into YAML String
String yamlOutput = yamlMapper.writeValueAsString(jsonNode);
System.out.println(yamlOutput);

How to implement Post API JSON with Spring?

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);

how to access jsonarray using retrofit

how to access districtID(key) value and name(key) value using retrofit ?
this is json file...
{
"error": false,
"message": "District successfully fetched.",
"districts": [
{
"districtID": "DIS260920181",
"name": "Raipur"
},
{
"districtID": "DIS260920182",
"name": "Bilaspur"
},
{
"districtID": "DIS011020186",
"name": "korba"
},
{
"districtID": "DIS011020187",
"name": "jagdalpur"
},
{
"districtID": "DIS021020188",
"name": "surguja"
},
{
"districtID": "DIS021020189",
"name": "Mungeli"
}
]
}
Please help :(
Convert JSON Array into POJO classes and then call api using retrofit network call.
Use this link
copy your json and it gives you two model class you should put the parent class which contains error , message and districts as your output in your request. something like this
#GET("your_url")
Call<ModelExample> nameOfMethod();
And then you have list of districts. you can access to the items and districtID and name
I hope it helps you :)
for onResponse:
--------------------------
Call<ModalClass> daoCall = api.getconnectdata();
modelclass.enqueue(new Callback<ModalClass>() {
#Override
public void onResponse(Call<ModalClass> call, Response<ModalClass>
response) {
if(response.isSuccessful()){
modelclass= response.body();
List<Districts> list = modelclass.getAddData().getData();
adapter = new CustomListAdapter(getApplicationContext(),list);
listView.setAdapter(adapter);
}
}

How to Parse Json response from REST webserivce using java

I have REST webservice which gives response in Json format, I have locally assigned the Json response in a variable. But now I want to know if we can parse and how. Below is a response from webservice.
{
"actionresult": "successful",
"licenceDetail": [
{
"licence": "SA123",
"type": "SZ Abalone",
"pendingtrip": [
],
"Vessel": [
{
"name": "Red Fire",
"number": "SA123"
}
],
"defaultvalue": {
"LandingPort": "Anxious Bay",
"DepartPort": "Acramans Creek",
"Vessel": "SA123",
"AreaFishing": "SA"
}
},
{
"licence": "K01",
"type": "Blue Crab",
"pendingtrip": [
],
"Vessel": [
{
"name": "Abrolhos Spirit",
"number": "K01"
}
],
"defaultvalue": null
}
]
}
Any help will be appreciated.
Regards,
Rohit
use Jackson2 library for converting json string into Object class.
I always use Gson. This is very easy to use.
Gson gson = new GsonBuilder().create();
MyClass myClass = gson.fromJson(jsonString, MyClass.class);
Maven dependency
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.4</version>
</dependency>
here you can read it in detail ObjectJson
JsonReader rdr = Json.createReader(is)) {
JsonObject obj = rdr.readObject();
JsonArray results = obj.getJsonArray("licenceDetail");
for (JsonObject result : results.getValuesAs(JsonObject.class)) {
String Landing result.getJsonObject("Default Value").getString("Landing port");
}

How to set http header in Json response

I've a CXF RESTful service which returns both XML and Json format. I need to add a custom http header in the RESTful service. Here's a sample code snippet.
#GET
#Path("/test")
#Produces("application/xml")
public Response test(
#QueryParam("p") String var
{
TestRequest req = new TestRequest();
req.setVar(var);
TestResponse res = p.getData(req);
return Response.ok(res).header("Result", res.getResult()).build();
}
The above code shows the XML response which sets the custom http header "Result". I'm able to see the new http header in the response header. So far so good.
Now, here's the Json version which internally calls the testService() method to get the result, then use google Gson API to send the result back. This has been working well, till I decided to return the new header. Here's the code snippet.
#GET
#Path("/test/jsonp")
public String testJSONP(
#QueryParam("p") String var,
#QueryParam("cb") String callBack
{
Response resp = test(var);
XStream xs = new XStream(new JsonHierarchicalStreamDriver());
xs.setMode(XStream.NO_REFERENCES);
xs.alias("TestResponse", TestResponse.class);
StringBuilder sb = new StringBuilder();
sb.append(callBack);
sb.append("(");
GsonBuilder gb = new GsonBuilder();
gb.registerTypeAdapter(XMLGregorianCalendar.class, new XMLGregorianCalenderSerializer());
gb.setPrettyPrinting();
Gson gson = gb.create();
sb.append(gson.toJson(resp));
sb.append(")");
return sb.toString();
}
I'm not able to see the http header in Json response.
Any feedback will be highly appreciated.
-Thanks
UPDATE
I added the following code in Json method for my testing.
#GET
#Path("/test/jsonp")
public String testJSONP(
#QueryParam("p") String var,
#QueryParam("cb") String callBack
{
Response resp = test(var);
XStream xs = new XStream(new JsonHierarchicalStreamDriver());
xs.setMode(XStream.NO_REFERENCES);
xs.alias("TestResponse", TestResponse.class);
StringBuilder sb = new StringBuilder();
sb.append(callBack);
sb.append("(");
GsonBuilder gb = new GsonBuilder();
gb.registerTypeAdapter(XMLGregorianCalendar.class, new XMLGregorianCalenderSerializer());
gb.setPrettyPrinting();
Gson gson = gb.create();
sb.append(gson.toJson(resp));
sb.append(")");
return Response.ok(sb.toString(), MediaType.APPLICATION_JSON).header("Result", "50").build();
}
This sets the header value correctly,but the issue is the Json response format seems to have changed. Since this is an existing service, I'm not allowed to do that.
Here's the existing response format
null({
"status": "Completed",
"totalResult": "252",
"bin": [
{
"type": "source",
"value": "documentation",
"ndocs": "243"
},
{
"type": "source",
"value": "wikihelp",
"ndocs": "6"
},
"entries": {
"item": [
{
"url": "http://test.com/test.htm",
"title": "\u003cspan class\u003d\"vivbold qt0\"\u003eXREF\u003c/span\u003e",
"snippet": " Test data.",
"source": "documentation",
"type": "html",
"shortDescription": "Starts the TEST command.",
"category": [
"User"
],
"publishDate": "2012-02-05T12:00:00-0500",
"lastUpdateDate": "2012-03-14T12:00:00-0400",
"topicId": "GUID-7DD70C3C-B8AD-40F1-8A69-5D1EECEAB013"
}
]
}
})
Here's the response after adding this change
null({
"status": 200,
"entity": {
"status": "Completed",
"totalResult": "252",
"bin": [
{
"type": "source",
"value": "documentation",
"ndocs": "243"
},
{
"type": "source",
"value": "wikihelp",
"ndocs": "6"
}
],
"entries": {
"item": [
{
"url": "http://test.com/test.htm",
"title": "\u003cspan class\u003d\"vivbold qt0\"\u003eXREF\u003c/span\u003e",
"snippet": " Test data.",
"source": "documentation",
"type": "html",
"shortDescription": "Starts the TEST command.",
"category": [
"User"
],
"publishDate": "2012-02-05T12:00:00-0800",
"lastUpdateDate": "2012-03-14T12:00:00-0700",
"topicId": "GUID-7DD70C3C-B8AD-40F1-8A69-5D1EECEAB013"
}
]
}
},
"metadata": {
"Result": {
}
}
})
You need to change signature of your method, to return an instance of Response class, instead of a String, and then built the response manually.
From the CXF wiki page:
#Path("/example")
public ExampleResource {
#GET
public Response getSomething() {
return Response.ok(/* some entity */).header("CustomHeader", "CustomValue").build();
}
}
Update
You can also inject HttpServletResponse into your handler using #Context annotation like this:
#Path("/example")
public class Welcome {
#GET
public String getSomething(
#QueryParam("p1") String param1,
#QueryParam("p2") String param2,
#Context HttpServletResponse response) {
response.addHeader("CustomHeader", "CustomValue");
return "my awesome response";
}
}
Note, that there is a CXF-1498 bug in versions prior to 2.1 that causes HttpServletResponse not being injected, so you need a newer CXF version.

Categories

Resources