Please help me to send a JSON object in POST HTTP request through HttpClient, in Android.
The problem I am facing is that the JSON object having the URL is replaced by forward slash ,i.e
originally it should have the following value in JSON object
{"product":
{"featured_src":"https:\/\/example.com\/wp-content\/uploads\/2015\/06\/sidney-compressed.jpg,
"short_description":"this is a test","title":"Raiders from the North"}
}
i tried many options to keep it in the above format. But it always comes as {"featured_src":
We assume this is your input
private final static String JSON_DATA = "{"
+ " \"product\": ["
+ " {"
+ " \"featured_src\": \"https:\\/\\/example.com\\/wp-content"
+ "\\/uploads\\/2015\\/06\\/sidney-compressed.jpg\","
+ " \"short_description\": \"this is a test\","
+ " \"title\" : \"Raiders from the North\""
+ " }"
+ " ]"
+ "}";
You could use replace to do the trick.
YOUR_STRING.replace("\\", "");
Finally your method would look like this, by passing your string as parameter
private static String jsonUrlCorrector(String json_data) {
json_data = json_data.replace("\\", "");
return json_data;
}
Here is the input:
{"product":[{"featured_src":"https:\/\/example.com\/wp-content\/uploads\/2015\/06\/sidney-compressed.jpg","short_description": "this is a test","title":"Raiders from the North"}]}
Here is the output
{"product":[{"featured_src":"https://example.com/wp-content/uploads/2015/06/sidney-compressed.jpg","short_description":"this is a test","title":"Raiders from the North"}]}
Related
I have a JSON payload saved as a String
String jsonBody = “{\n”
+ ” \“example\“: {\n”
+ ” \“example\“: [\n”
+ ” {\n”
+ ” \“example\“: 100,\n”
+ ” \“this_is_example_json_key\“: \“this_is_example_json_value\“,\n”
I created that by copying body from i.e Postman into
String jsonBody = "here I pasted the body";
Unfortunately I cannot have everything hardcoded there, so I have to change some values to variables. The JSON in postman looks like:
"this_is_example_json_key":"x"
And so on. Let's assume that:
String x = “this_is_example_json_value“;
If I just replace it like
+ ” \“this_is_example_json_key\“: \“ + x + \“,\n”
or something like that, the value in the body will be just this_is_example_json_value, where I need "this_is_example_json_value" (the "" marks are part of the value).
So the question is, how to set up those + / " in the String, so in the end in the value of the JSON I will end up with the value inside " ".
I've tried to play with the " / + but nothing of those were working. Variable must be passed with those " " because otherwise, the API is sending back an error.
Since java 15, if you want only use the string, you can also do in this way:
int this_is_example_json_value= 100;
String json = """
{
"this_is_example_json_key": %d
}
""".formatted(this_is_example_json_value);
Here the official jep.
Don't try to build up JSON using strings. Use a proper JSON parser.
import org.json.JSONException;
import org.json.JSONObject;
public class Eg {
public static void main(String[] args) throws JSONException {
String x = "this_is_example_json_value";
JSONObject example = new JSONObject();
example.put("this_is_example_json_key", x);
System.out.println(example.toString());
}
}
Which outputs:
{"this_is_example_json_key":"this_is_example_json_value"}
With no messing around wondering what needs to be escaped.
you can use an extra " \ " "
String x = "this_is_example_json_value";
String jsonBody = "{\n"
+ "\"example\": {\n"
+ " \"example\": [\n"
+ " {\n"
+ " \"example\": 100,\n"
+ "\"this_is_example_json_key\":" + "\"" + x + "\"" + "\n }"
+"\n ]\n }\n }";
in this case you will get a json string
{
"example": {
"example": [
{
"example": 100,
"this_is_example_json_key": "this_is_example_json_value"
}
]
}
}
This could be a duplicate question, but I couldn't find my solution anywhere. Hence, posting it.
I am trying to simply POST a request for a Student account Creation Scenario. I do have a JSON file which comprises all the "Keys:Values", required for Student account creation.
This is how the file student_Profile.json looks like:
{
"FirstName":"APi1-Stud-FN",
"MiddleInitial":"Q",
"LastName":"APi1-Stud-LN",
"UserAlternateEmail":"",
"SecretQuestionId":12,
"SecretQuestionAnswer":"Scot",
"UserName":"APi1-stud#xyz.com",
"VerifyUserName":"APi1-stud#xyz.com",
"Password":"A123456",
"VerifyPassword":"A123456",
"YKey":"123xyz",
"YId":6,
"Status":false,
"KeyCode":"",
"SsoUserName":"APi1-stud#xyz.com",
"SsoPassword":"",
"BirthYear":2001
}
So everything on Posting the request from "Rest Assured" point of view looks fine, it's just that I want to update a few values from the above JSON body using JAVA so that I can create a new Student profile every time I run my function and don't have to manually change the Body.
For Every POST Student Account Creation scenario, I need to update the value for
the following keys so that a new test student user account can be created:
First Name
Last Name and
Username // "VerifyUserName" and "SSO UserName" will remain same as user name
I modified the answer to get random values and pass them to json body. random value generation was taken from the accepted answer of this question.
public void testMethod() {
List<String> randomValueList = new ArrayList<>();
for (int i = 0; i < 3; i++) {
String SALTCHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
StringBuilder salt = new StringBuilder();
Random rnd = new Random();
while (salt.length() < 18) { // length of the random string.
int index = (int) (rnd.nextFloat() * SALTCHARS.length());
salt.append(SALTCHARS.charAt(index));
}
randomValueList.add(salt.toString());
}
String jsonBody = "{\n" +
" \"FirstName\":\"" + randomValueList.remove(0) + "\",\n" +
" \"MiddleInitial\":\"Q\",\n" +
" \"LastName\":\"" + randomValueList.remove(0) + "\",\n" +
" \"UserAlternateEmail\":\"\",\n" +
" \"SecretQuestionId\":12,\n" +
" \"SecretQuestionAnswer\":\"Scot\",\n" +
" \"UserName\":\"" + randomValueList.remove(0) + " \",\n" +
" \"VerifyUserName\":\"APi1-stud#xyz.com\",\n" +
" \"Password\":\"A123456\",\n" +
" \"VerifyPassword\":\"A123456\",\n" +
" \"YKey\":\"123xyz\",\n" +
" \"YId\":6,\n" +
" \"Status\":false,\n" +
" \"KeyCode\":\"\",\n" +
" \"SsoUserName\":\"APi1-stud#xyz.com\",\n" +
" \"SsoPassword\":\"\",\n" +
" \"BirthYear\":2001\n" +
"}";
Response response = RestAssured
.given()
.body(jsonBody)
.when()
.post("api_url")
.then()
.extract()
.response();
// Do what you need to do with the response body
}
We can used pojo based approach to do certain things very easily . No matter how complex is the payload , serialization and dieselization is the best answer . I have created a framework template for api automation that can we used by putting required POJO's in path :
https://github.com/tanuj-vishnoi/pojo_api_automation
To create pojo, I also have ready to eat food for you :
https://github.com/tanuj-vishnoi/pojo_generator_using_jsonschema2pojo
for the above problem you can refer to the JsonPath lib https://github.com/json-path/JsonPath and use this code:
String mypayload = "{\n" +
" \"FirstName\":\"APi1-Stud-FN\",\n" +
" \"MiddleInitial\":\"Q\",\n" +
" \"LastName\":\"APi1-Stud-LN\"}";
Map map = JsonPath.parse(mypayload).read("$",Map.class);
System.out.println(list);
once the payload converted into map you can change only required values as per the requirement
To generate random strings you can refer to lib org.apache.commons.lang3.RandomStringUtils;
public static String generateUniqueString(int lenghtOfString){
return
RandomStringUtils.randomAlphabetic(lenghtOfString).toLowerCase();
}
I recommend to store payload in a separate file and load it at runtime.
I have a JSONObject that is similar to something like this:
{
"category":"abc"
"staus":""open"
"external":[
{"name":"123", "type":"OTHER"},
{"name":"678", "type":"ALPHA"},
{"name":"890", "type":"DELTA"}
]
}
If I want to use JSONAssert to check if the item {"name":"678"} exists and I don't know the item's order and the number of items in the "external" array, how should I do in Java?
It seems the ArrayValueMatcher should be the way to go but I just cannot get it works.
Please help
You could use JsonPath for this usecase :
JSONArray array = JsonPath.read(json, "$.external[?(#.name == '678')]");
Assertions.assertThat(array).hasSize(1);
Here is a complete example using JsonAssert:
#Test
public void foo() throws Exception {
String jsonString = "{\n" +
" \"category\":\"abc\",\n" +
" \"staus\":\"open\",\n" +
" \"external\":[\n" +
" {\"name\":\"123\", \"type\":\"OTHER\"},\n" +
" {\"name\":\"678\", \"type\":\"ALPHA\"},\n" +
" {\"name\":\"890\", \"type\":\"DELTA\"}\n" +
" ]\n" +
"}";
JsonAssert.with(jsonString).assertThat("$.external[*].name", hasItem(equalTo("678")));
}
I am attempting to get the definition of a word using the documentation from Merriam Webster's API - https://dictionaryapi.com/products/json#sec-2.def
The documentation shows the structure of the JSON response from the server, and I have been able to successfully parse the raw data into a just an array containing the "sense" object.
Screenshot of code and parsed data
My issue is being able to access the "sense" JSONObject, since I am currently in an array, I can't access the sense object. I have tried adding .getJSONArray(0) and .getJSONObject(0) after my code and both of those solutions did not work.
How can I continue parsing this JSON I currently have to the "dt" string?
JSONArray merriamResults = data.getJSONArray("Merriam")
.getJSONObject(0)
.getJSONArray("def")
.getJSONObject(0)
.getJSONArray("sseq")
.getJSONArray(0)
.getJSONArray(0);
Here.
String json = "{\"def\":[\n" +
" {\n" +
" \"sseq\":[\n" +
" [\n" +
" [\n" +
" \"sense\",\n" +
" {\n" +
" \"dt\":[[\"text\",\"{bc}a {a_link|backward} somersault especially\n" +
" in the air\"]]\n" +
" }\n" +
" ]\n" +
" ]\n" +
" ]\n" +
" }\n" +
"]}";
try {
JSONObject jsonObject = new JSONObject(json);
String dt = jsonObject.getJSONArray("def")
.getJSONObject(0)
.getJSONArray("sseq")
.getJSONArray(0)
.getJSONArray(0)
.getJSONObject(1)
.getJSONArray("dt")
.getJSONArray(0)
.getString(1);
Log.i("jsondata", dt);
} catch (JSONException e) {
e.printStackTrace();
}
my log:
12-02 21:38:12.316 14174-14174/com.example.pemba.sample I/jsondata: {bc}a {a_link|backward} somersault especially
in the air
{
"lastUpdated":1404620562,
"invasions":{
"Vibrant Valley":{
"asOf":1404620562,
"type":"Penny Pincher",
"progress":"959/1000"
}
},
"error":null
}
I'm new to using Json & Gson so be patient.
So I am attempting to make an application for myself that allows me to view the information from this json file. The only problem is that it is constantly changing and sometimes there will be more then one object under invasions or sometimes there will be none. How would I parse this with gson? Thanks. Note I am grabbing values from here.
https://www.toontownrewritten.com/api/invasions
Thanks!
Use the JsonParser class
String myJson = "{" +
" \"lastUpdated\":1404620562," +
" \"invasions\":{" +
" \"Vibrant Valley\":{" +
" \"asOf\":1404620562," +
" \"type\":\"Penny Pincher\"," +
" \"progress\":\"959/1000\"" +
" }" +
" }," +
" \"error\":null" +
"}"
JsonElement jelement = new JsonParser().parse(myJson);
JsonObject jobject = jelement.getAsJsonObject();
long lastUpdated = jobject.get("lastUpdated").getAsLong();