how to create a json enclosed with square brackets in java? - json

I generate a json with the following code.
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
HashMap<String,String> map = new HashMap<String,String>();
map.put("Message","All");
list.add(map);
Gson gson = new Gson();
String userResponseListValue = gson.toJson(map);
I get the json in the following format
{"Message":"All"}
I need the json to be in the following format
[{"Message":"All"}]
Since I'm new to gson i can't fix this problem. can some one guide me to fix this problem.

Square brackets denote a list or array, so try outputting the list you already prepared but are not using:
gson.toJson(list);

Brackets [] denote an Array in JSON, and what you have is a HashMap, not an Array...
You can manually add the square brackets like:
String userResponseListValue = "[ " + gson.toJson(map) + " ]";
Or create a ArrayList<HashMap>.
EDIT: In fact, you have the Array, but you're not using it! Try:
String userResponseListValue = gson.toJson(list);

Related

Enumerating of JObject of NewtonSoft.Json loses '\' character in C#

I would like to parse json string using JObject.Parse() of NewtonSoft.Json. Assume that the json string is like this:
{"json":"{\"count\":\"123\"}"}
The result of jObject.First.ToString() is "json": "{\"count\":\"123\"}".
The result of jObject["json"].ToString() is {"count":"123"}. Enumerating gets the same result as this.
The testing code I used is like this.
[TestMethod()]
public void JsonParseTest()
{
var json = "{\"json\":\"{\\\"count\\\":\\\"123\\\"}\"}";
var jObject = JObject.Parse(json);
Console.WriteLine($"json : {json}");
Console.WriteLine($"jObject.First.ToString() : {jObject.First}");
Console.WriteLine($"jObject[\"json\"].ToString() : {jObject["json"]}");
}
We can see that enumerating of jObject will lose the character '\'. What is the problem? I would be appreciated for any suggestion :)
EDIT 1
The version of NewtonSoft is 12.0.3 released in 2019.11.09.
The parser isn't loosing anything. There is no literal \ in your example. The backslashes are purely part of the JSON syntax to escape the " inside the string vlue. The value of the key json is {"count":"123"}.
If you want to have backslashes in that value (however I don't see why you would want that), then you need add them, just like you added them in your C# string (C# and JSON happen to have the same escaping mechanism):
{"json":"{\\\"count\\\":\\\"123\\\"}"}
with leads to the C# code:
var json = "{\"json\":\"{\\\\\\\"count\\\\\\\":\\\\\\\"123\\\\\\\"}\"}";

JsonSlurper parsing String containing Json into unexpected format

From a separate system I get a String parameter "messageJson" whose content is in the form:
{"agent1":"smith","agent2":"brown","agent3":{"agent3_1":"jones","agent3_2":"johnson"}}
To use it in my program I parse it with JsonSlurper.
def myJson = new JsonSlurper().parseText(messageJson)
But the resulting Json has the form:
[agent1:smith, agent2:brown, agent3:[agent3_1:jones, agent3_2:johnson]]
Note the square brackets and the lack of double quotes. How can I parse messageJson so that the original structure is kept?
Ok, thanks to the hint by cfrick, I was able to find a solution. In case anyone else has a similar problem, all I needed to do was using JsonOutput in the end to convert the map back to a Json
I.E. :
def myJson = new JsonSlurper().parseText(messageJson)
myJson << [agent4:"jane"]
def backToJson = JsonOutput.toJson(myJson)

How to replace a JSON value stored in a JSON file and use that in a Rest Assured test

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"));

JSON is printed with backslashes

{"externalQueryDate":"4018-11-23"}
this is my json string, which is in a column of mysql.
I get it with creditRisk.getCreditRiskDataCodeBased()
and in javascript or in swagger, i see with backslashes:
"{\"externalQueryDate\":\"4018-11-23\"}"
I can use JSON.parse in frontend but , i want to solve this is backend.
even
for
StringWriter sw = new StringWriter();
objectMapper.writer().writeValue(sw, creditRisk.getCreditRiskDataTermBased());
it writes this:
"responseCode": "\"{\\\"externalQueryDate\\\":\\\"4018-11-23\\\"}\""
I tried those
objectMapper.readTree(creditRisk.getCreditRiskDataCodeBased()).toString()
and
objectMapper.writer().writeValue(sw, creditRisk.getCreditRiskDataTermBased());
and
#JsonRawValue
#JsonValue
How can i solve this?
In mysql, it is also without slashes
If you want to parse the json string with jackson objectMapper you need to use 'read' and tell it what class to use to create the parsed object from.
So in your case you could do something like
ObjectMapper objectMapper = new ObjectMapper();
String json = "{\"externalQueryDate\":\"4018-11-23\"}";
Map map = objectMapper.readValue(json, Map.class);
System.out.print(map.get("externalQueryDate"));
I've just used a Map here as I don't know what class you're wanting to parse the json into. If you have a class with an externalQueryDate field you can read into that. You could also use #JsonFormat on the field to tell it what the date format is if you want to parse the value straight into a LocalDate field.
I suggest you write a few simple unit tests to get the hang of escaped quotes in strings. It looks like they're causing you some confusion.

want to bind string using comma separated using for loop

string json="[{\"ParentId\":\"a9764da3147845c184bd272cef6a5937\",\"Path\":\"/LMS/Cabinet/bdc2cd8e1da3451c84e332d1aa74f605\",\"CreatedBY\":\"admin\",\"IsActive\":\"Y\",\"CabinetName\":\"LMS\",\"FolderTag\":\"IT mobile computing,Comm Skills\",\"Name\":\"JAVA\",\"UpdatedBY\":\"\",\"Type\":\"Folder\",\"IsDelete\":\"N\",\"UpdatedON\":\"\",\"Id\":\"bdc2cd8e1da3451c84e332d1aa74f605\",\"CreatedON\":\"2015_09_08-11:19:50\",\"TemplateId\":\"dd42c8a71a954c1d948ef35492ee1242\" },{\"ParentId\":\"a9764da3147845c184bd272cef6a5937\",\"Path\":\"/LMS/Cabinet/3aae020c256f4dc1ab705af67bede2c7\",\"CreatedBY\":\"admin\",\"IsActive\":\"Y\",\"CabinetName\":\"LMS\",\"FolderTag\":\"IT mobile computing,Comm Skills\",\"Name\":\"Spring\",\"UpdatedBY\":\"\",\"Type\":\"Folder\",\"IsDelete\":\"N\",\"UpdatedON\":\"\",\"Id\":\"3aae020c256f4dc1ab705af67bede2c7\",\"CreatedON\":\"2015_09_04-16:58:05\",\"TemplateId\":\"dd42c8a71a954c1d948ef35492ee1242\"},{\"ParentId\":\"a9764da3147845c184bd272cef6a5937\",\"Path\":\"/LMS/Cabinet/c139b33a22a94a25bf624b94450aee3e\",\"CreatedBY\":\"admin\",\"IsActive\":\"Y\",\"CabinetName\":\"LMS\",\"FolderTag\":\"Social Skills\",\"Name\":\"SQL\",\"UpdatedBY\":\"\",\"Type\":\"Folder\",\"IsDelete\":\"N\",\"UpdatedON\":\"\",\"Id\":\"c139b33a22a94a25bf624b94450aee3e\",\"CreatedON\":\"2015_09_04-16:54:44\",\"TemplateId\":\"dd42c8a71a954c1d948ef35492ee1242\"}]";
This is my JSON string and I want to only "Name" field with comma separated into another variable.
For example, example:
string res={"JAVA","SPRING","SQL"}
What language are you trying to do this in? My first guess is javascript but i wasnt sure.
If its JavaScript, then you can get starten by turning the json string into a JavaScript object like this:
var jsonElements = JSON.parse (json);
From there its just looping and collecting the name property from each object.
Now we'll do this from C# instead
Ok, since you are doing the parsing from C# you would want this code instead:
string json = "[{\"ParentId\":\"a9764da3147845c184bd272cef6a5937\",\"Path\":\"/LMS/Cabinet/bdc2cd8e1da3451c84e332d1aa74f605\",\"CreatedBY\":\"admin\",\"IsActive\":\"Y\",\"CabinetName\":\"LMS\",\"FolderTag\":\"IT mobile computing,Comm Skills\",\"Name\":\"JAVA\",\"UpdatedBY\":\"\",\"Type\":\"Folder\",\"IsDelete\":\"N\",\"UpdatedON\":\"\",\"Id\":\"bdc2cd8e1da3451c84e332d1aa74f605\",\"CreatedON\":\"2015_09_08-11:19:50\",\"TemplateId\":\"dd42c8a71a954c1d948ef35492ee1242\" },{\"ParentId\":\"a9764da3147845c184bd272cef6a5937\",\"Path\":\"/LMS/Cabinet/3aae020c256f4dc1ab705af67bede2c7\",\"CreatedBY\":\"admin\",\"IsActive\":\"Y\",\"CabinetName\":\"LMS\",\"FolderTag\":\"IT mobile computing,Comm Skills\",\"Name\":\"Spring\",\"UpdatedBY\":\"\",\"Type\":\"Folder\",\"IsDelete\":\"N\",\"UpdatedON\":\"\",\"Id\":\"3aae020c256f4dc1ab705af67bede2c7\",\"CreatedON\":\"2015_09_04-16:58:05\",\"TemplateId\":\"dd42c8a71a954c1d948ef35492ee1242\"},{\"ParentId\":\"a9764da3147845c184bd272cef6a5937\",\"Path\":\"/LMS/Cabinet/c139b33a22a94a25bf624b94450aee3e\",\"CreatedBY\":\"admin\",\"IsActive\":\"Y\",\"CabinetName\":\"LMS\",\"FolderTag\":\"Social Skills\",\"Name\":\"SQL\",\"UpdatedBY\":\"\",\"Type\":\"Folder\",\"IsDelete\":\"N\",\"UpdatedON\":\"\",\"Id\":\"c139b33a22a94a25bf624b94450aee3e\",\"CreatedON\":\"2015_09_04-16:54:44\",\"TemplateId\":\"dd42c8a71a954c1d948ef35492ee1242\"}]";
dynamic jsonObj = (JArray)JsonConvert.DeserializeObject(json);
List<string> names = new List<string>();
foreach (JObject item in jsonObj)
{
names.Add(item["Name"].ToString());
}
Deserialize the string and cast it to a JArray. Then foreach element in the array, we look at the Name property of the element. I tested this code in visual studio and it appears to work.