Jolt don't transform json to another json - java

I am writing a project using Java 11, spring boot 2.1.9 and jolt (core and utils) 0.1.1 on Ubuntu
I have next JSON source:
{
"restaurant": {
"rating": {
"value": 3
},
"address": {
"value": "India"
}
}
}
And I have the following spec file:
[
{
"operation": "shift",
"spec": {
"restaurant": {
"rating": {
"value": "Restaurant Rating"
}
}
}
}
]
On the output I expect next json:
{
"Restaurant Rating" : 3
}
I wrote a simple test to check this:
List<Object> specs = JsonUtils.jsonToList(Files.readString(Paths.get("path/to/spec.json")));
Chainr converter = Chainr.fromSpec(specs);
Object inputJSON = JsonUtils.toJsonString(Files.readString(Paths.get("path/to/example.json")));
Object transformedOutput = converter.transform(inputJSON);
System.out.println(JsonUtils.toPrettyJsonString(transformedOutput));
But variable transformedOutput always is null
Please tell me what I'm doing wrong.

jsonToObject will get input json as object and map with spec
List specs = JsonUtils.jsonToList(Files.readString(Paths.get("path/to/spec.json")));
Chainr converter = Chainr.fromSpec(specs);
Object inputJSON = JsonUtils.jsonToObject(Files.readString(Paths.get("path/to/example.json")));
Object transformedOutput = converter.transform(inputJSON);
System.out.println(JsonUtils.toPrettyJsonString(transformedOutput));
----output-----
{
"Restaurant Rating" : 3
}

Related

Chainr.transform giving Null as transformedObject

I'm working on a requirement to convert JSONObject from one to another with the help of Jolt.
The source input i'm passing as :
{
"a":"ABC",
"b":"ABC1",
"c":1,
"d":2,
"e":"ABC2",
"details":
{
"a1": "ABC3",
"b1": "ABC4",
"c1": 3,
"d1": "ABC5",
"e1": "ABC6",
"f1": "ABC7"
}
}
I need in form of
{
"ConvertedOutput" : {
"X1" : "ABC1",
"Y1" : "ABC4"
}
}
Spec i used :
[
{
"operation": "shift",
"spec": {
"b": "ConvertedOutput.X1",
"details": {
"b1": "ConvertedOutput.Y1"
}
}
}
]
I'm able to get the proper output from : https://jolt-demo.appspot.com/#inception. But when i use same spec via code Chainr.transform returning null.
Code part
List<Object> transformJsonSpec = JsonUtils.classpathToList("inputSpecJSONPath");
final Chainr chainr = Chainr.fromSpec(transformJsonSpec);
Object transformedOutput = chainr.transform(payload);
System.out.println("transformSpec Str " + transformJsonSpec.toString());
System.out.println("transformSpec " + transformJsonSpec);
System.out.println("transformedOutput " + transformedOutput);
System.out.println(" jolt transform " + JsonUtils.toJsonString(transformedOutput));
The payload needs to be converted using JsonUtils.jsonToObject if you are passing in a String:
Object transformedOutput = chainr.transform(JsonUtils.jsonToObject(payload));

JSON to JSON Transform of input sample using any existing java library/tools

Input:
{
"Student": {
"name" :"abc",
"id" : 588,
"class : "12"
}
}
Reqired Output:
{
"Student": {
"key" :"name",
"value":"abc",
"key" :"id",
"value":"588",
"key" :"class",
"value":"12"
}
}
Your output json invalid. Json object can not duplicate key .
You can use the library org.json and do something like this:
JSONObject jsonObject = new JSONObject(inputJson);
JSONObject outputJson = new JSONObject();
JSONArray array = new JSONArray();
for (Object key : jsonObject.keySet()) {
JSONObject item = new JSONObject();
String keyStr = (String)key;
Object keyvalue = jsonObj.get(keyStr);
item.put(keyStr, keyvalue);
array.put(item);
}
outputJson.put("Student", array);
System.out.println(json.toString());
Output :
{
"Student": [
{
"key": "name",
"value": "abc"
},
{
"key": "id",
"value": "588"
},
{
"key": "class",
"value": "12"
}
]
}
Similar to the other answer, the desired output JSON format is not valid.
The closest valid output would be
{
"Student" : [ {
"key" : "name",
"value" : "abc"
}, {
"key" : "id",
"value" : 588
}, {
"key" : "class",
"value" : "12"
} ]
}
This can be generated via Jolt with the following spec
[
{
"operation": "shift",
"spec": {
"Student": {
"name": {
"$": "Student[0].key",
"#": "Student[0].value"
},
"id": {
"$": "Student[1].key",
"#": "Student[1].value"
},
"class": {
"$": "Student[2].key",
"#": "Student[2].value"
}
}
}
}
]
This is easy to solve with JSLT if we assume the output is made valid JSON by making an array of key/value objects like the other respondents do.
The array function converts an object into an array of key/value objects exactly like you ask for, so the transform becomes:
{"Student" : array(.Student)}

How to get the JSON array values without have JSON object values in android? Is it Possible?

How to convert following type Json array in "tags_name": ["Activity Based"] in android and store data using getter setter methods.How to create POJO class, and how to handle when array is empty.I am struck with this concept.I tried this following way. Please guide me to resolve this issue.
API
"postlist": [
{
"posts": {
"pm_post_id": "4647",
},
"tags_name": [
"Activity Based"
],
"images_count": 0,
"images": [],
"post_user": [
{
"first_name": "Michelle",
"last_name": "Smith",
"profile_pic": "profess_sw_engg.jpg"
}
],
"is_encourage_user": true,
"encourage_feed_id": "992"
},
{
"posts": {
"pm_post_id": "4647",
},
"tags_name": [],
"images_count": 2,
"images": [
{
"gallery_id": "5549",
"name": "IMG_20161012_1832491.jpg",
},
{
"gallery_id": "5550",
"name": "IMG_20161012_1832441.jpg",
}
],
"post_user": [
{
"first_name": "Michelle",
"last_name": "Smith",
"profile_pic": "profess_sw_engg.jpg"
}
],
"is_encourage_user": true,
"encourage_feed_id": "993"
}
]
In Java i've use Following code.
try {
JSONArray tagNameArr = tempPostObject.getJSONArray("tags_name");
for(int iloop=0;i<tagNameArr.length();iloop++)
{
String street = tagNameArr.getString(iloop);
Log.i("..........",""+street);
}
} catch (Exception e) {
e.printStackTrace();
}
try this to get value of tags_name JSONArray.
ArrayList<String> temp = new ArrayList<String>();
JSONArray tagName= jsonResponse.getJSONArray("tags_name");
for(int j=0;j<tagName.length();j++){
temp.add(tagName.getString(j));
}
Use jsonschema2pojo.org service and Gson converter (lib from Google). select Gson converter on the site.
You can use gson
Gson gson = new GsonBuilder().serializeNulls().create();
RestaurantLoginResponseClass restaurantLoginResponse = gson.fromJson(loginResponseJsonString, RestaurantLoginResponseClass.class);
Add dependencies in app.gradle
compile 'com.google.code.gson:gson:2.6.2'
#MohanRaj , why you would to parse it ! , it is not clear , if you would to get the values and retain it in java object or save it in file system , you can use :
Gs
Gson gson = new Gson();
Staff obj = gson.fromJson(jsonInString, Staff.class);
if you have a list of object inside your json
you can create a list in your staff class something like :
#SerializedName("hits")
private List<Car> cars = new ArrayList<Car>();
GSON can understood it and parse the incoming list to those object .
you can get POJO from familiar JSON to java POJO tools :
http://www.jsonschema2pojo.org/
and you can check for more info https://sites.google.com/site/gson/gson-user-guide
http://www.java2blog.com/2013/11/gson-example-read-and-write-json.html

rest assured check the name is exist in the json response

Am new to rest assured.Using rest assured am trying to verify data detail is found or not.Here two data details present.Some times it will be 2 or 3 or 5
Am getting response as follows and using java
{
"queryPath": "/api/",
"nId": "f084f5ad24fcfaa9e9faea0",
"statusCode": 707
"statusMessage": "Success",
"results": {
"data": [
{
"id": "10248522500798",
"capabilities": [
"record",
"HDt"
],
"name": "errt2"
},
{
"id": "418143778",
"capabilities": [
"1record",
"HDy"
],
"name": "Livin"
}
]
}
}
code using
JsonPath jsonResponse = new JsonPath(response.asString());
ArrayList<String> list = new ArrayList<String>();
list = jsonResponse.get("results.data"); //
if (list.size() < 1 ) {
SpiceCheck.fail("data not found! " + list.size());
}
Rather than this i wwant to check the data name is null or not also.How can i do that rest assured.
Just so you know you are missing a comma after 707.
To verify that none of the names is null I would parse out the names as a list, then iterate over the names one by one and check that they aren't null.
List<String> names = from(response.asString()).getList("results.data.name");
for(String name : names){
if(name == null){
// error handling code here
}
}

How to decode JSONObject

This question is related with my previous question
I can successfully get the String in json format from the URL to my spring controller
Now I have to decode it
so I did like the following
#RequestMapping("/saveName")
#ResponseBody
public String saveName(String acc)
{jsonObject = new JSONObject();
try
{
System.out.println(acc);
org.json.JSONObject convertJSON=new org.json.JSONObject(acc);
org.json.JSONObject newJSON = convertJSON.getJSONObject("nameservice");
System.out.println(newJSON.toString());
convertJSON = new org.json.JSONObject(newJSON.toString());
System.out.println(jsonObject.getString("id"));
}
catch(Exception e)
{
e.printStackTrace();jsonObject.accumulate("result", "Error Occured ");
}
return jsonObject.toString();
}
This is the JSON String { "nameservice": [ { "id": 7413, "name": "ask" }, { "id": 7414, "name": "josn" }, { "id": 7415, "name": "john" }, { "id": 7418, "name": "RjhjhjR" } ] }
When I run the code then I get the error
org.json.JSONException: JSONObject["nameservice"] is not a JSONObject.
What wrong I am doing?
It's not a JSONObject, it's a JSONArray
From your question:
{ "nameservice": [ { "id": 7413, "name": "ask" }, { "id": 7414, "name": "josn" }, { "id": 7415, "name": "john" }, { "id": 7418, "name": "RjhjhjR" } ] }
The [ after the nameservice key tells you it's an array. It'd need to be a { to indicate an object, but it isn't
So, change your code to use it as a JSONArray, then iterate over the contents of that to get the JSONObjects inside it, eg
JSONArray nameservice = convertJSON.getJSONArray("nameservice");
for (int i=0; i<nameservice.length(); i++) {
JSONObject details = nameservice.getJSONObject(i);
// process the object here, eg
System.out.println("ID is " + details.get("id"));
System.out.println("Name is " + details.get("name"));
}
See the JSONArray javadocs for more details
It seems you're trying to get a JSONObject when "nameservice" is an array of JSONObjects and not an object itself. You should try this:
JSONObject json = new JSONObject(acc);
JSONArray jsonarr = json.getJSONArray("nameservice");
for (int i = 0; i < jsonarr.length(); i++) {
JSONObject nameservice = jsonarr.getJSONObject(i);
String id = nameservice.getString("id");
String name = nameservice.getString("name");
}
I don't understand why you do it manualy if you already have Spring Framework.
Take a look at MappingJackson2HttpMessageConverter and configure your ServletDispatcher accordingly. Spring will automatically convert your objects to JSON string and vice versa.
After that your controller method will be looked like:
#RequestMapping("/saveName")
#ResponseBody
public Object saveName(#RequestBody SomeObject obj) {
SomeObject newObj = doSomething(obj);
return newObj;
}

Categories