How to insert the json data Array into existing json field? - json

I have the following JSON:
{
"X":20,
"Y":null
}
Now, for the key Y, i need to insert below json array.
{
"A":null,
"B":1,
"C":5000,
"D":0.25
}
I tried this but doesn't work:
String response1 =
given()
.cookie(apiTestSessionID)
//.spec(requestSpecification)
.when()
//.get("/service/bill/Config")
.get("/service/bill/Config/0001")
.asString();
JsonPath jsonCstmrConfig = new JsonPath(response);
String response2 = given()
.cookie(apiTestSessionID)
.when()
.get("/service/commoncache/card")
.asString();
JsonPath jsonSoiRateCard = new JsonPath(response2);
Map<String,String> maps = jsonCstmrConfig.getMap("data");
maps.put("X","Value");
Is there any way to do it with provided rest assured json library.

Try below code, it uses Gson library
Gson gson = new Gson();
String response1 = given()
.cookie(apiTestSessionID)
.when()
.get("/service/bill/Config/0001")
.asString();
//Converting response string to JsonObject
JsonObject jsonObj = gson.fromJson (jsonStr, JsonElement.class).getAsJsonObject();
String response2 = given()
.cookie(apiTestSessionID)
.when()
.get("/service/commoncache/card")
.asString();
//Converting response string to JsonElement
JsonElement element = gson.fromJson (response2, JsonElement.class);
//Adding json data array to existing jsonObject
jsonObj.add("Y", element);

Related

jsonobject for nested api's put operation

i am trying to put request by using jsonobject but i couldnt find a way to send it
how can i create put body for api like
{
"roleRight": {
"systemSetting": 0,
"userManagement": 0
}
}
right now, i created like;
public static JSONObject nspRightSet(String ssvalue, String umvalue) {
JSONObject requestParams = new JSONObject();
requestParams.put("roleRight.systemSetting", ssvalue);
requestParams.put("roleRight.userManagement", umvalue);
return requestParams;
}
and use it by;
res = given()
.header("Authorization", "Bearer " + localLogin.accessToken)
.header("Content-type", "application/json")
.contentType(ContentType.JSON)
.body(nspRightSetBody)
.when()
.put("https://localhost:8090/api/v1/roles/" + rolenameId + "/right")
.then()
.log().all()
.statusCode(201)
.extract()
.response().getBody();
}
but it gives error like;
"error": "JSON parse error: Cannot deserialize instance of `...` out of START_ARRAY token;
public static JSONObject nspRightSet(String ssvalue, String umvalue) {
JSONObject requestParams = new JSONObject();
JSONObject childJSON = new JSONObject();
childJSON.put("systemSetting", ssvalue);
childJSON.put("userManagement", umvalue);
requestParams.put("roleRight", childJSON);
return requestParams;
}

Convert JSON response of LinkedHashmap List to Custom Java Response object

I came across a weird scenario.
I was calling a External API which is returning Lists of LinkedHashMap (E.g: List<LinkedHashMap<String, String>)
So the question is how to convert this JSON response to Custom Response object in Java
Use the below code to convert JSON response to Custom Response object in Java.
ResponseEntity<Object> response = restTemplate.exchange(
pathURL,
HttpMethod.{GET/POST ..},
createHeader(),
Object.class
);
final List<LinkedHashMap> responseList = objectMapper
.convertValue(
response.getBody(),
new TypeReference<List<LinkedHashMap>>() {
}
);
LinkedHashMap<String, String> responseMap = responseList.get(0);
CustomResponseObj infoResp = objectMapper.convertValue(responseMap, CustomResponseObj.class);
private HttpEntity<?> createHeader() {
HttpHeaders headers = new HttpHeaders();
return new HttpEntity<>(headers);
}

read data from a json formatted object

I have a .net application in which I am getting a response data in json format. I have used the below code to get the json response.
string details= new System.Net.WebClient().DownloadString(url);
var temp = JsonConvert.DeserializeObject(details.ToString());
I have got a json format object in temp and json format string in details
I am getting an output as below from temp
{"data":
[
{"category":"Community","name":"New Page","access_token":"accesstoken_data1","perms":["ADMINISTER","EDIT_PROFILE","CREATE_CONTENT","MODERATE_CONTENT","CREATE_ADS","BASIC_ADMIN"],"id":"1234"},
{"category":"Community","name":"Page ABC","access_token":"accesstoken_data2","perms":["ADMINISTER","EDIT_PROFILE","CREATE_CONTENT","MODERATE_CONTENT","CREATE_ADS","BASIC_ADMIN"],"id":"56789"}
]
,"paging":{"next":"https:\/\/graph.facebook.com\/1100234567\/accounts?access_token=pageAccesstoken&limit=5000&offset=5000&__after_id=77786543"}
}
I need to get the category,name,access_token as key and corresponding data as values in some dictionary.
How can I achieve it?
Hope this will do the required stuffs
private Dictionary<string, object> deserializeToDictionary(string jo)
{
var values = JsonConvert.DeserializeObject<Dictionary<string, object>>(jo);
var values2 = new Dictionary<string, object>();
foreach (KeyValuePair<string, object> d in values)
{
if (d.Value.GetType().FullName.Contains("Newtonsoft.Json.Linq.JObject"))
{
values2.Add(d.Key, deserializeToDictionary(d.Value.ToString()));
}
else
{
values2.Add(d.Key, d.Value);
}
}
return values2;
}
This was taken from the following link
How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?
string json = #"{""key1"":""value1"",""key2"":""value2""}";
Dictionary<string, string> values = JsonConvert.DeserializeObject<Dictionary<string, string>
More examples: Serializing Collections with Json.NET

Using Gson and JsonObject to format and parse data

I am using JsonObject and Gson to format the data i need to send in the form of String and then retrieve and parse it somewhere else.
This is my simple code which is not working:
public static void main(String[] args)
{
Gson g = new Gson();
Gson listG = new Gson();
ArrayList<String> l= new ArrayList<String>();
l.add("abcd");
l.add("efgh");
l.add("ijkl");
String list = listG.toJson(l);
JsonObject jObject = new JsonObject();
jObject.addProperty("command" , 1);
jObject.addProperty("message" , "this is a test message");
jObject.addProperty("list" , list);
String toSend = g.toJson(jObject);
System.out.println(toSend);
Gson rec = new Gson();
JsonObject newObj = rec.fromJson(toSend, JsonObject.class);
System.out.println(newObj); // getting nothing in newObj
}
What am i doing wrong here?
You should use:
JsonObject newObj = new JsonParser().parse(toSend).getAsJsonObject();
Lots of calls in there, but the gist is to use the JsonParser class.

how to convert a JSON code to map

use the org.json.jar
I know convert a JSON code to JSONObject
JSONObject fieldsJson = new JSONObject("{\"a\":\"b\"}");
String value= fieldsJson.getString("a");
But how to convert a JSON code to map
String str = "{\"age\":\"23\",\"name\":\"ganlu\"}";
JSONObject jobj = JSONObject.fromObject(str);
Map<String,String> tmpMap = (Map) JSONObject.toBean(jobj,Map.class);
Set<String> keys = tmpMap.keySet();
for(String key : keys){
System.out.println(key+":"+tmpMap.get(key));
}
May this will help you.