how to escape part of json loaded as object - java

I'm not fluent in API testing hence my question. I have a body to POST (mock) that will consist of:
{
"request":
{
"urlPath": "path/to/",
"method": "POST",
"bodyPatterns":[{
"equalToJson" : "{\n\"query\": [\n{\n\"name\": \"name1\",\n\"value\": \"123\"\n },\n{\n\"name\": \"name2\",\n\"value\": \"345\"\n},\n{\n\"name\": \"name3\",\n\"value\": \"someName\"\n}\n],\n\"anotherItem\": [],\n\"side\": 77,\n\"pageSize\": 44\n}", "jsonCompareMode": "LENIENT"
}]
},
"response":
{
"status": 200,
"headers":
{
"Content-Type" : "application/json"
},
"body": "{"items\": [\n{\n\"item\": 1,\n
\"item2\": 2,\n
etc
"\n}\n]\n}"
}
}
I want to use some pojo classes to separately create Request and Response:
public Request initRequest() {
BodyPattern bodyPat = new BodyPattern();
Query query = new Query();
Query query2 = new Query();
Query query3 = new Query();
EqualToJson equalToJ = new EqualToJson();
query.setName("name1");
query.setValue("123");
query2.setName("name2");
query2.setValue("345");
query3.setName("name2");
query3.setValue("someName");
List<Query> queryList = new ArrayList<>();
queryList.add(query);
queryList.add(query2);
queryList.add(query3);
equalToJ.setQuery(queryList);
List<Filter> filtersList = new ArrayList<>();
equalToJ.setFilter(filtersList);
equalToJ.setSide(77);
equalToJ.setPageSize(44);
List<EqualToJson> eqList = new ArrayList<>();
eqList.add(equalToJ);
req.setUrlPath(URL + "/Test001");
req.setMethod("POST");
bodyPat.setEqualToJson(eqList);
bodyPat.setJsonCompareMode("LENIENT");
List<BodyPattern> bodyPatList = new ArrayList<>();
bodyPatList.add(bodyPat);
req.setBodyPatterns(bodyPatList);
return req;
}
To see it in more user-friendly view, here you go:
{
"request": {
"urlPath": "/path/to",
"method": "POST",
"bodyPatterns": [
{
"equalToJson": {
"query": [
{
"name": "name1",
"value": "123"
},
{
"name": "name2",
"value": "345"
},
{
"name": "name3",
"value": "someName"
}
],
"filter": [
],
"side": 77,
"pageSize": 44
},
"jsonCompareMode": "LENIENT"
}
]
},
"response": {
"status": 200,
"headers": {
"Content-Type": "application/json"
},
"body": {
"side": 77,
"pageSize": 44,
"items": [
{
"name1": "123",
"name2": "345",
"name3": "someName"
etc...
}
]
}
}
}
Similarly, I do with Response.
My question is, how can I make to have just a part of this json (BodyPatters) as escaped signs? Mock is created this way that it only accepts escaped characters in this part of json.
I can of course hardcode this payload, but I want to have control over those fields' values and steer them, as parameters.
I really have no idea how to handle this.

You can use objectmapper of jackson to convert Object to String. For example:
void name2() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
Query query = new Query("name1", "123");
EqualToJson equalToJson = new EqualToJson();
equalToJson.setQuery(Arrays.asList(query));
BodyPattern bodyPattern = new BodyPattern();
bodyPattern.setEqualToJson(mapper.writeValueAsString(equalToJson));
String bodyPatternText = mapper.writerWithDefaultPrettyPrinter()
.writeValueAsString(bodyPattern);
System.out.println(bodyPatternText);
}
#Data
#AllArgsConstructor
static class Query{
private String name;
private String value;
}
#Data
static class EqualToJson {
private List<Query> query;
}
#Data
static class BodyPattern {
private String equalToJson;
}
This is a result:
{
"equalToJson" : "{\"query\":[{\"name\":\"name1\",\"value\":\"123\"}]}"
}

Related

Java Spring response JSON String unescaped

I have the following Spring Method :
#RequestMapping(value = "/product/{productId}", method = RequestMethod.GET ,produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> getProductById(
//ProductDTO database query in order to retrieve productg by ID and population
final ObjectMapper objectMapper = new ObjectMapper();
final String json = objectMapper.writeValueAsString(productDTO);
return new ResponseEntity<>(json, HttpStatus.OK);
That returns a product representation in JSON format, the problem that I have is when I return this JSON , in the response I get it escaped like this:
"{\"uid\":\"test\",\"type\":\"Fragrance\",\"modifiedtime\":1575379505000,\"name\":\"test
name\",\"otherProperties\":{\"container\":false,\" ETC...``
I would need it unescaped in the response , how can I achieve this?
The reason I transform the DTO manually is because if I just return the DTO in the ResponseEntity the representation of the JSON handled by Spring is not the same as the one I get using objectMapper.writeValueAsString method , instead of getting this:
"name": "nombre de prueba",
"otherProperties": {
"container": false,
"onlineExclusive": false,
"sizeGuide": "size guide",etc..
I get this:
"name": "nombre de prueba",
"otherProperties": [
{
"key": "container",
"value": {
"type": "boolean",
"value": false
}
},
{
"key": "onlineExclusive",
"value": {
"type": "boolean",
"value": false
}
},
{
"key": "sizeGuide",
"value": {
"type": "string",
"value": "size guide"
}
},
```

How do I insert a Json node into another one in Java?

I have one Json node:
{
"name":
{
"first": "Tatu",
"last": "Saloranta"
},
"title": "Jackson founder",
"company": "FasterXML"
}
I have another Json node (the one which I want to insert):
{
"country": "My country",
"hobbies": "some hobbies"
}
I want my resulting node to be:
{
"additional info":
{
"country": "My country",
"hobbies": "some hobbies"
},
"name":
{
"first": "Tatu",
"last": "Saloranta"
},
"title": "Jackson founder",
"company": "FasterXML"
}
How do I do that in Java? Here is my java code:
private final static ObjectMapper JSON_MAPPER = new ObjectMapper();
JsonNode biggerNode = parseTree(someObject);
JsonNode nodeToBeInsertede = JSON_MAPPER.valueToTree(anotheObj);
//I want to do something like this:
//biggerNode.put("additionalInfo", nodeToBeInsertede)
Instead of JsonNode read a Map and use standard Map.put() to modify the bigger object:
ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
TypeReference<Map<String, Object>> type = new TypeReference<>() {};
Map<String, Object> biggerMap = mapper.readValue(biggerJson, type);
Map<String, Object> smallerMap = mapper.readValue(smallerJson, type);
biggerMap.put("additional_info", smallerMap);
String outJson = mapper.writeValueAsString(biggerMap);
System.out.println(outJson);
will output:
{
"name" : {
"first" : "Tatu",
"last" : "Saloranta"
},
"title" : "Jackson founder",
"company" : "FasterXML",
"additional_info" : {
"country" : "My country",
"hobbies" : "some hobbies"
}
}

How can I make a JSON object, the output will be like this?

I am very new to json, How can I make a JSON object the structure (output string)would be like this? I am using the org.json library.
Is this a json array contians json array?
I have input like this:
111(root)
----222(child of 111)
--------333(child of 222)
--------444(child of 222)
----123(child of 111)
--------456(child of 123)
--------456(child of 123)
How can I make a json the output would be like blow,
{
"name": "flare",
"children": [
{
"name": "analytics",
"children": [
{
"name": "cluster",
"children": [
{
"name": "AgglomerativeCluster",
"value": 3938
},
{
"name": "CommunityStructure",
"value": 3812
}
]
},
{
"name": "graph",
"children": [
{
"name": "BetweennessCentrality",
"value": 3534
},
{
"name": "LinkDistance",
"value": 5731
}
]
}
]
},
{
"name": "animate",
"children": [
{
"name": "Easing",
"value": 17010
},
{
"name": "FunctionSequence",
"value": 5842
}
]
}
]
}
Thanks for you help!
You can change your dependency and use a library that allows Object mapping such as Jackson, or you can do the mapping by hand as follows:
private static JSONObject toJSONObject(String name, Object value) {
JSONObject ret = new JSONObject();
ret.put("name", name);
if (value != null) {
ret.put("value", value);
}
return ret;
}
public static JSONObject addChildren(JSONObject parent, JSONObject... children) {
parent.put("children", Arrays.asList(children));
return parent;
}
public static void main(String[] sargs) {
JSONObject flare = toJSONObject("flare", null);
addChildren(flare,
addChildren(toJSONObject("analytics", null),
addChildren(toJSONObject("cluster", null),
toJSONObject("AgglomerativeCluster", 3938),
toJSONObject("CommunityStructure", 3812)
),
addChildren(toJSONObject("graph", null),
toJSONObject("BetweennessCentrality", 3534),
toJSONObject("LinkDistance", 5731)
)
),
addChildren(toJSONObject("animate", null),
toJSONObject("Easing", 17010),
toJSONObject("FunctionSequence", 5842)
)
);
System.out.println(flare.toString());
}
You can simply have class like this.
public class Node {
String name;
List<Node> children;
String value;
}
This can be achieved by ObjectMapper's pretty print.
public String pretty(Object object) throws JsonProcessingException {
return OBJECT_MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(object);
}
You may use my library for it.
<dependency>
<artifactId>json-utils</artifactId>
<groupId>org.bitbucket.swattu</groupId>
<version>1.0.16</version>
</dependency>
new JsonUtil().pretty(object);

unable to parse a valid JSON String

I am trying to parse a JSON String and map it to a hashmap, I have a valid JSONString from server but when I traverse through it, all I can get it is the first result.
JSONArray peoples = null;
ArrayList<HashMap<String, String>> personList = new ArrayList<HashMap<String,String>>();
JSONObject jsonObj = new JSONObject(value);
Log.d("Jello",jsonObj.toString());
peoples = jsonObj.getJSONArray("product");//check here
Log.d("Jello",peoples.toString());
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String service_group = c.getString("sgroup");
String service = c.getString("service");
String value = c.getString("value");
String updated_at = c.getString("updated_at");
HashMap<String,String> persons = new HashMap<String,String>();
persons.put("service_group",service_group);
persons.put("service",service);
persons.put("value",value);
persons.put("updated_at",updated_at);
personList.add(persons);
}
My JSON String is :
{"product":[{"sgroup":"Dummy_BIG_ONE","service":"Dummy_UNDER_BIG_ONE","code":"128","value":"0","updated_at":"2015-12-04 21:21:00"}]}{"product":[{"sgroup":"Hello Monkey","service":"Do u work","code":"123","value":"0","updated_at":"2015-12-04 21:27:51"}]}{"product":[{"sgroup":"Checking from Android Device","service":"Monkey","code":"12345","value":"0","updated_at":"2015-12-04 22:55:39"}]}{"product":[{"sgroup":"Checking from Android Device","service":"Monkey","code":"12345","value":"0","updated_at":"2015-12-04 22:55:40"}]}{"product":[{"sgroup":"Checking from Android Device","service":"Monkey","code":"12345","value":"0","updated_at":"2015-12-04 22:55:42"}]}{"product":[{"sgroup":"Hello World","service":"Donkey","code":"24411","value":"0","updated_at":"2015-12-04 22:57:05"}]}{"product":[{"sgroup":"lkfnhjdiofho","service":"dfjdifj","code":"1101","value":"0","updated_at":"2015-12-05 01:15:49"}]}{"product":[{"sgroup":"Baal","service":"Saal","code":"1234","value":"21","updated_at":"2015-12-05 01:34:59"}]}{"product":[{"sgroup":"Inis","service":"Mona","code":"1234","value":"1001","updated_at":"2015-12-05 01:39:51"}]}{"product":[{"sgroup":"Medical Treatment Loan","service":"Number of referral slip","code":"128","value":"0","updated_at":"2015-12-05 01:50:42"}]}{"product":[{"sgroup":"Medical Treatment Loan","service":"Number of referral slip","code":"128","value":"0","updated_at":"2015-12-05 01:55:12"}]}{"product":[{"sgroup":"Medical Treatment Loan","service":"Number of referral slip","code":"128","value":"1000","updated_at":"2015-12-05 01:56:10"}]}
or HERE
here is how I am sending the JSON
while($row = mysql_fetch_assoc($output))
{
$product = array();
$product["sgroup"] = $row["service_group"];
$product["service"] = $row["service"];
$product["code"] = $row["code"];
$product["value"] = $row["amount"];
$product["updated_at"] = $row["updated_at"];
// user node
$response["product"] = array();
array_push($response["product"], $product);
// echoing JSON response
echo json_encode($response);
}
I want to add all the data's from the JSON in my ArrayList so that I can use it later.
Thank you for your help.
First, there are online tools available to determine if your JSON is valid.
Here is a general example of a better way to format your JSON data:
<?php
$bigArray = array();
for ($x = 0; $x <= 10; $x++) {
$product = array();
$product["sgroup"] = $x;
$product["service"] = $x;
$product["code"] = $x;
$product["value"] = $x;
$product["updated_at"] = $x;
array_push($bigArray, $product);
}
// echoing JSON response
echo json_encode($bigArray);
?>
Which gives this valid JSON response that is simple and easy to parse:
[
{
"sgroup":0,
"service":0,
"code":0,
"value":0,
"updated_at":0
},
{
"sgroup":1,
"service":1,
"code":1,
"value":1,
"updated_at":1
},
{
"sgroup":2,
"service":2,
"code":2,
"value":2,
"updated_at":2
},
{
"sgroup":3,
"service":3,
"code":3,
"value":3,
"updated_at":3
},
{
"sgroup":4,
"service":4,
"code":4,
"value":4,
"updated_at":4
},
{
"sgroup":5,
"service":5,
"code":5,
"value":5,
"updated_at":5
},
{
"sgroup":6,
"service":6,
"code":6,
"value":6,
"updated_at":6
},
{
"sgroup":7,
"service":7,
"code":7,
"value":7,
"updated_at":7
},
{
"sgroup":8,
"service":8,
"code":8,
"value":8,
"updated_at":8
},
{
"sgroup":9,
"service":9,
"code":9,
"value":9,
"updated_at":9
},
{
"sgroup":10,
"service":10,
"code":10,
"value":10,
"updated_at":10
}
]
As for the parsing, using a HashMap is not the best way. Create a list of Person POJO objects.
First define the Person class:
class Person {
public String group;
public String service;
public String value;
public String updated;
public Person(String g, String s, String v, String u) {
group = g;
service = s;
value = v;
updated = u;
}
}
Then, parsing is fairly simple:
List<Person> personList = new ArrayList<>();
JSONArray jsonArr;
try {
jsonArr = new JSONArray(response);
for(int i=0;i<jsonArr.length();i++){
JSONObject c = jsonArr.getJSONObject(i);
String service_group = c.getString("sgroup");
String service = c.getString("service");
String value = c.getString("value");
String updated_at = c.getString("updated_at");
Person p = new Person(service_group, service, value, updated_at);
personList.add(p);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You should put your products into json array:
[
{
"product": {
"sgroup": "lkfnhjdiofho",
"service": "dfjdifj",
"code": "1101",
"value": "0",
"updated_at": "2015-12-05 01:15:49"
}
},
{
"product": {
"sgroup": "Baal",
"service": "Saal",
"code": "1234",
"value": "21",
"updated_at": "2015-12-05 01:34:59"
}
},
{
"product": {
"sgroup": "Inis",
"service": "Mona",
"code": "1234",
"value": "1001",
"updated_at": "2015-12-05 01:39:51"
}
},
{
"product": {
"sgroup": "Medical Treatment Loan",
"service": "Number of referral slip",
"code": "128",
"value": "0",
"updated_at": "2015-12-05 01:50:42"
}
},
{
"product": {
"sgroup": "Medical Treatment Loan",
"service": "Number of referral slip",
"code": "128",
"value": "0",
"updated_at": "2015-12-05 01:55:12"
}
},
{
"product": {
"sgroup": "Medical Treatment Loan",
"service": "Number of referral slip",
"code": "128",
"value": "1000",
"updated_at": "2015-12-05 01:56:10"
}
}
]
And you have to change your parser little bit:
JSONArray jsonArray = new JSONArray(string);
for(int i=0;i<jsonArray.length();i++){
JSONObject c = jsonArray.getJSONObject(i).getJSONObject("product");
String service_group = c.getString("sgroup");
String service = c.getString("service");
String value = c.getString("value");
String updated_at = c.getString("updated_at");
HashMap<String,String> persons = new HashMap<String,String>();
persons.put("service_group",service_group);
persons.put("service",service);
persons.put("value",value);
persons.put("updated_at",updated_at);
personList.add(persons);
}
You don't need put your object into "product" attribute, but directly into array :
[
{
"sgroup": "lkfnhjdiofho",
"service": "dfjdifj",
"code": "1101",
"value": "0",
"updated_at": "2015-12-05 01:15:49"
},
{
"sgroup": "Baal",
"service": "Saal",
"code": "1234",
"value": "21",
"updated_at": "2015-12-05 01:34:59"
},

Use gson to convert json that should be array of objects, but isn't

{"myContainer" :
{ "couldBeAnything" : [
{"id":1, "name":"sb", "category":"couldBeAnything"},
{"id":2, "name":"bs", "category":"couldBeAnything"}
],
"somethingElse" : [
{"id":1, "name":"sdsa","category":"somethingElse"},
{"id":2, "name":"ve","category":"somethingElse"}
]
},
"id" : 0
}
So far I have :
Type myContainerType = new TypeToken<MyContainer>(){}.getType();
MyContainerType myContainerType = gson.fromJson(myJson.getValue(), myContainerType);
Where
public class MyContainer {
private int id;
private Map<String, List<Foo>> foo; // and foo has id, name, category
The result, no errors, a populated id field, but just a null map
I think the json is wrong for the structure Map<String, List<Foo>>. When you say map you need not enclose each key-value with {. Just put the whole key values in one {} and seprate with commas. eg
{
"myContainer": {
"couldBeAnything": [
{
"id": 1,
"name": "sb",
"category": "couldBeAnything"
},
{
"id": 2,
"name": "bs",
"category": "couldBeAnything"
}
],
"somethingElse": [
{
"id": 1,
"name": "sdsa",
"category": "somethingElse"
},
{
"id": 2,
"name": "ve",
"category": "somethingElse"
}
]
},
"id": 0
}
With this json it works perfectly
public static void main(String[] args){
String json = "{\"myContainer\":{\"couldBeAnything\":[{\"id\":1,\"name\":\"sb\",\"category\":\"couldBeAnything\"},{\"id\":2,\"name\":\"bs\",\"category\":\"couldBeAnything\"}],\"somethingElse\":[{\"id\":1,\"name\":\"sdsa\",\"category\":\"somethingElse\"},{\"id\":2,\"name\":\"ve\",\"category\":\"somethingElse\"}]},\"id\":0}";
Map<String, List<Foo>> obj = new HashMap<String, List<Foo>>();
Gson gson = new Gson();
obj = gson.fromJson(json, obj.getClass());
System.out.println(obj);
}
Output
{id=0.0, myContainer={couldBeAnything=[{id=1.0, name=sb, category=couldBeAnything}, {id=2.0, name=bs, category=couldBeAnything}], somethingElse=[{id=1.0, name=sdsa, category=somethingElse}, {id=2.0, name=ve, category=somethingElse}]}}
The issue with your approach was the naming of the field foo. Your json contains the Map<String, List<Foo>> name as myContainer. So modify your container class like below and it will work fine :)
public class MyContainer {
private int id;
private Map<String, List<Foo>> myContainer;
}
Now this will work
Type myContainerType = new TypeToken<MyContainer>(){}.getType();
MyContainer myContainer = gson.fromJson(json, myContainerType);
System.out.println(myContainer);

Categories