I want to use the following JSON in my code in Java:
[
{
"speed": 200
}
]
I tried to write this line :
JSONObject jsonBody = new JSONObject("[{\"speed\": 200}]");
But I always get an error. What is the exact format that I have to use here??
EDIT: So it would be more proper to use a JSONArray rather than use a JSONObject (as my last post said)
So the correct java code would be
String json = "[{\"speed\": 200}]";
System.out.println(json);
JSONArray jsonBody = new JSONArray(json);
System.out.println(jsonBody.getJSONObject(0).get("speed"));
Related
The Json body I want to deserialize is something like below
{
"status": "OK",
"place_id": "07e0a63d862b2982e4c4b7e655f148d2",
"scope": "APP"
}
Below is the Json body I want to build from above Json after deserializing it
{
"place_id": "07e0a63d862b2982e4c4b7e655f148d2"
}
Because your JSON data appears to be rather small you could use Gson's JsonParser.parseString(String) method to parse the data into an in-memory representation, then copy the relevant JSON object member to a new JsonObject and serialize that to JSON using Gson.toJson(JsonElement):
JsonObject original = JsonParser.parseString(json).getAsJsonObject();
JsonObject copy = new JsonObject();
// Might also have to add some validation to make sure the member
// exists and is a string
copy.add("place_id", original.get("place_id"));
String transformedJson = new Gson().toJson(copy);
If this solution turns out to not be efficient enough for you, you could also have a look at JsonReader and JsonWriter.
I have a set of input data files in JSON and I am trying to replace a value present in a JSON file and use that value to do a post request in restAssured
The JSON file has
{
"items": [
{
"item_ref": 241,
"price": 100
}
]
}
jsonbody below is a String of the above JSON file
This is the code that fails:
JSONObject jObject = new JSONObject(jsonbody);
jObject.remove("item_ref");
jObject.put("item_ref","251");
System.out.println(jObject);
This is what I am getting:
{"item_ref":"251","items":[{"item_ref":241,"price":100}]}
What I want is {"items":[{"item_ref":251,"price":100}]}
I also tried
JSONObject jObject = new JSONObject(jsonbody);
jObject.getJSONObject("items").remove("item_ref");
jObject.getJSONObject("items").put("item_ref","251");
System
But it says JSONObject["items"] is not a JSONObject.
All I need is to replace the 241 with 251. Is there an easier way to do this?
In general if we have a predefined JSON body file and if we want to replace some of the values in the body and use that in our POST calls within RestAssured, is there any easier way to do it?
The problem is - field item_ref and price are not in JSON Object as you think they are.
They are in JSON Array which contains JSON Objects. In order to modify that value, you have to get elements of the array and THEN execute very similar code you wrote.
Check this out:
JSONObject jObject = new JSONObject(jsonbody);
JSONArray array = jObject.getJSONArray("items");
JSONObject itemObject = (JSONObject) array.get(0); //here we get first JSON Object in the JSON Array
itemObject.remove("item_ref");
itemObject.put("item_ref", 251);
The output is:
{"items":[{"item_ref":251,"price":100}]}
Also, you can create a Hashmap:
HashMap<String,String> map = new HashMap<>();
map.put("key", "value");
RestAssured.baseURI = BASE_URL;
RequestSpecification request = RestAssured.given();
request.auth().preemptive().basic("Username", "Password").body(map).put("url");
System.out.println("The value of the field after change is: " + map.get("key"));
So I'm trying to split a json array with some metadata and append the metadata to each object in the array:
{
"#version":"1",
"metadata":{"key1":"value1","key2":"value2"},
"messages":[{"msg":{...}},{"msg":{...}}, ... ]
}
to
{
"type":"msg",
"data":{
"#version":"1",
"metadata":{"key1":"value1","key2":"value2"},
"msg":{...}
}
}
I have the following Camel route which almost works:
from("direct:kafkaMsg")
.routeId("rKafkaMsg")
.log(DEBUG, "JSON: ${body}")
.setHeader("#version").jsonpath("$.#version")
.setHeader("metadata").jsonpathWriteAsString("$.metadata") // not writing as string
.split().jsonpathWriteAsString("$.messages..msg")
.setHeader("msgId", jsonpath("$.msgNo"))
.setHeader("kafka.KEY", simple("${header.msgId}"))
.setBody(simple("{\"type\":\"msg\","
+ "\"data\":{\"#version\":\"${header.#version}\",\"metadata\":${header.metadata},"
+ "\"msg\":${body}}}"))
.log(DEBUG, "body: ${body}")
.log(INFO, "msgPush: writing msg to kafka - msgId: ${header.msgId}")
.setProperty(Exchange.CHARSET_NAME, constant("UTF-8"))
.to("kafka:sometopic?partitioner=" + DefaultPartitioner.class.getName())
.end();
But the Json I actually get like this is:
{
"type":"msg",
"data":{
"#version":"1",
"metadata":{key1="value1",key2="value2"}, // wrong. This looks like mapToString
"msg":{...}
}
}
When I had .split().jsonpath("$.messages..msg") before, the 'msg' object was also wrongly formatted in the output but jsonpathWriteAsString() helped in this case. I also tried jsonpath("$.metadata", String.class) but it did not help.
Does anybody know how to fix this? Thanks.
I solved this using a workaround involving a Processor:
.split().jsonpath("$.messages..msg")
.setHeader("msgId", jsonpath("$.msgNo"))
.setHeader("kafka.KEY", simple("${header.msgId}"))
// Processor instead of setBody()
.process(exchange -> {
JsonObject data = new JsonObject();
data.put("#version", exchange.getIn().getHeader("#version"));
data.put("metadata", exchange.getIn().getHeader("metadata"));
data.put("msg", exchange.getIn().getBody());
JsonObject body = new JsonObject();
body.put("type", "msg");
body.put("data", data);
exchange.getOut().setBody(body.toJson());
exchange.getOut().setHeaders(exchange.getIn().getHeaders());
})
I prefer this solution anyway because I don't have to write part of the json string myself.
I am using org.json to convert an xml to json using below code snippet.Unfotunately, there is a structure called "countries" which is supposed to be an array, but can have only 1 country sometimes. In such cases, array is not getting disaplyed instead "countries" is showing up under {} instead of [{}] or [].
JSONObject xmlJSONObj = XML.toJSONObject(xsltresponse);
return xmlJSONObj.toString(PRETTY_PRINT_INDENT_FACTOR);
output i am getting is with after json conversion is:
{
"data":{
"name":"Microsoft",
"date":"today",
"countries":{
"name:"AN"
}}}
Instead of getting below output
{
"data":{
"name":"Microsoft",
"date":"today",
"countries":[{
"name:"AN"
}]
}}
How do i fix it?
I used this to arrive at solution, this works fine. I will mark it as accepted answer. Please let me know other wise.
JSONObject xmlJSONObj = XML.toJSONObject(response);
JSONArray jsonArray = new JSONArray();
JSONObject data = xmlJSONObj.getJSONObject("data");
JSONObject objArr = data.optJSONObject("countries");
if (objArr != null) {
jsonArray.put(objArr);
data.putOpt("countries", jsonArray);
}
I am storing the response of a REST Get request and trying to access as below,
final JSONObject receivedItem = new JSONObject(response.readEntity(String.class));
This is the sample response,
[
{
"timeStamp": 1511136000000,
"contextKeys": [
{
"tKey": "Test1",
"contextKey": "Location",
"contextValue": "San Jose",
"eCount": 3
},
{
"tKey": "Test1",
"contextKey": "Name",
"contextValue": "User1",
"eCount": 3
}
}
]
And i am getting the below error,
org.json.JSONException: A JSONObject text must begin with '{' at character 1
at org.json.JSONTokener.syntaxError(JSONTokener.java:496)
at org.json.JSONObject.<init>(JSONObject.java:180)
at org.json.JSONObject.<init>(JSONObject.java:403)
Any clues ?
Thanks
As Rajkumar pointed out, in your example there is a missing close bracket - but this may just be a simple typing error.
The actual error message is saying A JSONObject text must begin with '{' which is because JSON objects are exactly that, objects. You need to use a JSONArray to parse your example JSON as follows:
final JSONArray receivedItem = new JSONArray(response.readEntity(String.class));
This may change some of your other code to handle this as an array vs an object.
If your problem is with storing and accessing json response try this response instead;
I am presuming that you are using javascript; Anyways, core idea is the same;
var jsonStorage;
$.getJSON('your url',(json) => {
jsonStorage = json;
});
console.log(jsonStorage) //your jsonresponse is now available here;