serialize a json using gson - json

I am using com.google.gson.JsonObject to send the json inside 'parameters' to a rest endpoint.
{
"parameters":
"{
\"customer\" : {
\"firstName\": \"Temp\",
\"lastName\": \"Temp\",
\"emailAddresses\": [\"temp1#temp.com\"],
\"address\": {
\"street1\": \"123 W Temp St\",
\"city\": \"Temp\",
\"state\": \"Illinois\",
\"zipCode\": \"61122\"
}
},
\"options\" : [\"tv\"]
}"
}
Since Parameters is a json string, I am trying to do this :
JsonObject json = new JsonObject();
json.addProperty("options", ??);
I am not sure how to do it for customer and options.
'options' is a java Set, whereas customer is an object.

You may use:
Gson gson = new Gson();
String json = "{\"parameters\": {\"customer\" ... ";
JsonObject jsonObject = gson.fromJson(json, JsonObject.class);
JsonArray options = new JsonArray();
options.add("tv");
jsonObject.add("options", options);
String output = gson.toJson(jsonObject);

Related

how to convert nested payload into Java-JSONObject (net.minidev.json.JSONObject) for Restassured POST call

How to convert below nested payload into Java-JSONObject (net.minidev.json.JSONObject) for Restassured POST call request body ?
{
"object": "new_subway_group",
"name": "Group 1",
"subways": [
1,
2,
3
]
}
Setup request body, use array or List for [1,2,3]
JSONObject surveyPriceObject = new JSONObject();
surveyPriceObject.put("object", "new_subway_group");
surveyPriceObject.put("name", "Group 1");
surveyPriceObject.put("subways", Arrays.asList(1,2,3));
Convert response to JSONObject
If the response has type Response then
import net.minidev.json.JSONObject;
...
JSONObject object = res.jsonPath().getObject("", JSONObject.class);
System.out.println(object);
If the response has type String then
import io.restassured.path.json.JsonPath;
import net.minidev.json.JSONObject;
...
JSONObject object = JsonPath.from(res).getObject("", JSONObject.class);
System.out.println(object);

Nested JSON Objects in Kotlin with Volley

I am very new to this as you can probably tell, but i'm trying to parse a JSON url with Volley using Kotlin in Android Studio. The url contains nested Objects, not nested Arrays.
I can display everything inside "questionnaire", but I only want to display "typeOfQuestion". How do i do that?
MainActivity.kt:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
questionTV = findViewById(R.id.idTVQuestion)
answerTV = findViewById(R.id.idTVAnswer)
typeTV = findViewById(R.id.idTVType)
val queue: RequestQueue = Volley.newRequestQueue(applicationContext)
val request = JsonObjectRequest(Request.Method.GET, url, null, { response ->
loadingPB.setVisibility(View.GONE)
try {
val question: String = response.getString("question")
val answer: String = response.getString("answer")
val typeOfQuestion: String = response.getString("typeOfQuestion")
questionTV.text = question
answerTV.text = answer
typeTV.text = typeOfQuestion
} catch (e: Exception) {
e.printStackTrace()
}
}, { error ->
Log.e("TAG", "RESPONSE IS $error")
Toast.makeText(this#MainActivity, "Fail to get response", Toast.LENGTH_SHORT)
.show()
})
queue.add(request)
}
}
Heres the JSON:
{
"questionnaire": {
"question": "Where do you live?",
"answer": "In the mountains",
"typeOfQuestion": "Informative
}
}
You have object inside another json object.If you need to access field from child object you need to get child jsonObject and then get fields from object.
var questionnaire = response.getJSONObject("questionnaire")
You need to get fields from questionnaire object.Like.
val question: String = questionnaire.getString("question")
val answer: String = questionnaire.getString("answer")
val typeOfQuestion: String = questionnaire.getString("typeOfQuestion")

Rest Assured - compare json response with local json file

I have a local json file test.json
[
{
"id": 1,
"title": "test1"
},
{
"id": 2,
"title": "test2"
}
]
Class to read the json file
public static String getFileContent(String fileName){
String fileContent = "";
String filePath = "filePath";
try {
fileContent = new String(Files.readAllBytes(Paths.get(filePath)));
return fileContent;
}catch(Exception ex){
ex.printStackTrace();
}finally{
return fileContent;
}
}
I use rest assured to make the request and get same json response back
String fileContent= FileUtils.getFileContent("test.json");
when().
get("/testurl").
then().
body("", equalTo(fileContent));
This is what I got from local file
[\r\n {\r\n \"id\": 1,\r\n \"title\": \"test1\"\r\n },\r\n {\r\n \"id\": 2,\r\n \"title\": \"test2\"\r\n }\r\n]
This is the actual response:
[{id=1, title=test1}, {id=2, title=test2}]
Is there any better way to compare those two? I try to do something like fileContent.replaceAll("\\r\\n| |\"", ""); but it just removed all the space [{id:1,title:test1},{id:2,title:test2}]
Any help? Or any ways that just compare the content and ignore newline, space and double quote?
You can use any of the following methods
JsonPath :
String fileContent = FileUtils.getFileContent("test.json");
JsonPath expectedJson = new JsonPath(fileContent);
given().when().get("/testurl").then().body("", equalTo(expectedJson.getList("")));
Jackson :
String fileContent = FileUtils.getFileContent("test.json");
String def = given().when().get("/testurl").then().extract().asString();
ObjectMapper mapper = new ObjectMapper();
JsonNode expected = mapper.readTree(fileContent);
JsonNode actual = mapper.readTree(def);
Assert.assertEquals(actual,expected);
GSON :
String fileContent = FileUtils.getFileContent("test.json");
String def = given().when().get("/testurl").then().extract().asString();
JsonParser parser = new JsonParser();
JsonElement expected = parser.parse(fileContent);
JsonElement actual = parser.parse(def);
Assert.assertEquals(actual,expected);

creating json as is shown in Postman

I'm trying to post data via API to InsightVM. I keep getting error 400 which means wrong format. I break it down, the problem is in hostnames part.
JSONObject json = new JSONObject();
JSONArray array = new JSONArray();
if (host_info.getDataType() == dataType.Web_Vulnerability && methodType == MethodType.Add_host_To_Site)
{
JSONObject json2 = new JSONObject();
json2.put("name",host_info.getHost_fqdn());
json2.put("source", "Splunk");
array.add(json2);
DateTimeFormatter dtf = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
json.put("date",OffsetDateTime.now().format(dtf) );
json.put("ip",host_info.getHost_ip());
json.put("os",host_info.getOperating_system());
json.put("hostNames",array); // problem is here
}
is the code above provide the same format as below:
{
"date": "2019-05-20",
"ip": "00.00.00.00",
"os":"Linux",
"hostNames":
[
{
"name": "corporate-workstation-1102DC.acme.com",
"source": "Splunk"
}
]
}
JSONArray implements Collection.
While JSONObject has an overloaded put() method,
which takes a Collection and wraps it in a JSONArray which might be causing the problem.
Can you try the following -
jsonObject.put("hostNames",(Object)array);

Parsing nested JSON array in android

I am trying to parse this json in android and displaying the contents in list.
I am able to retrieve title,location and creator but dont know how to get inside des_update and retrieve text on '0'
[
{
"title": "my event ",
"location": "Chennai, Tamil Nadu, India",
"creator": "abc",
"des_update": {
"0": "this is my event with moderator"
}
},
{
"title": "my event 17",
"location": "pune",
"creator": "abc",
"des_update": {}
}
]
this is my parsing code I want to display data in alist
// convert json string to json array
JSONArray aJson = new JSONArray(sJson);
// create apps list
List<events> apps = new ArrayList<events>();
for(int i=0; i<aJson.length(); i++) {
JSONObject json = aJson.getJSONObject(i);
events app = new events();
app.setTitle(json.getString("title"));
app.setDate(json.getString("date"));
app.setLocation(json.getString("location"));
// add the app to apps list
apps.add(app);
...
}
you can use the following code:
JSONArray jsonArray = new JSONArray(json);
JSONObject object = jsonArray.getJSONObject(0);
JSONObject desObject = object.getJSONObject("des_update");
String data = desObject.getString("0");
System.out.println(data);
Here first you are loading your json string into JSONArray, and then you are taking one object from JSONArray instance. As des_update is an object with in the object you need to get that object calling getJSONObject() by passing your key and from there you can load the data that you want to use.
JSONArray jsonArray = new JSONArray(jsonString);
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject object = jsonArray.getJSONObject(i);
String title = object.getString("title");
String location = object.getString("location");
String creator = object.getString("creator");
JSONObject des_update = object.getJSONObject("des_update");
String str = des_update.getString("0");
System.out.println("des_update-------" + str);
}