I'm wondering how can I escape HTML code in JSON ? I'm using Jackson as my JSON mapper.
In my content I have various characters: tags, single quotes, double quotes, new lines character (\n), tabs etc. I tried to use CharacterEscapes class, but with no results.
My JSON response blows up after using CharacterEscapes. I tried to escape it manually, but also without any results.
So the question is, lets say that we have:
<p>Some text</p>\n<p>"SomeText"</p>
How can I send it back to browser as value of the JSON object?
UPDATE:
Input is:
{
"code": {
"num": 12
},
"obj": {
"label": "somelabel",
"order": 1
},
"det": {
"part": "1",
"cont": true
},
"html": "<p>Mine text</p>"
}
Output:
{
"code": {
"num": 12
},
"obj": {
"label": "somelabel",
"order": 1
},
"det": {
"part":"1",
"cont": true
},
"html":{"code": {
"num": 12
},
"obj": {
"label": "somelabel",
"order": 1
},
"det": {
"part":"
}
For now I have found following solution:
I have added CharacterEscapes to the JsonFactory of the ObjectMapper class.
Also I have changed way of writting JSON into response.
Instead of
objectMapper.writeValue(response.getWriter(), myObject)
I'm doing this:
PrintWriter writer = response.getWriter();
writer.print(String.valueOf(objectMapper.writeValueAsBytes(myObject));
writer.flush();
And it works as I wanted.
I would suggest to use either of below.
1.You can use GSON library for this purpose.
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
2.Use Apache commons StringEscapeUtils.escapeHtml("JSON string").
Related
I need to transform a Json into another Json according to the parameter coming as part of Rest request. This service is developed in Java. I know, Jackson API can be used easily and there are some libraries also available. But my requirement is to delivery response with new Json faster as much as possible.
If I can be given few option I can measure the performance of those.
Let's assume I have this Json in data storage:
{
"bookId": "23228232-2dfa232",
"bookName": "Json Transformation",
"bookPublisher": "Tech Publication",
"bookRating": [
{
"source": "All book rank",
"maxRating": "10",
"rating": "3.4"
},
{
"source": "Tech Books",
"maxRating": "5",
"rating": "2"
},
{
"source": "Popular",
"maxRating": "3",
"rating": "1"
}
],
"bookAuthor": [
{
"name": "Jone",
"specialities": [
"Json",
"Javascript",
"Typescript",
"nodejs"
]
},
{
"name": "Mike",
"specialities": [
"Java",
"Spring",
"ElasticSearch"
]
}
]
}
Below rest calls should have respective results from this Json:
Get only authors
/authorName/23228232-2dfa232
{
authorName: [
"Jone",
"Mike"
]
}
Get Average Rating
/popularity/23228232-2dfa232
{
rating: "1.78"
}
So, the question is how to do this kind of transformation efficiently with any available library? As I mentioned above, I can simply use any Json library in Java and transform the Json, but I am not sure, if that will be efficient.
You can try little json java library for searching json data.
JsonValue json = JsonParser.parse(stringvariablewithjsondata);
List<JsonValue> authors = json.findAll(SPM.path("bookAuthor", "name")));
List<String> ratings = json.findAllLiterals(SPM.path("bookRating", "rating")));
and compute result like
JsonArray values = JsonFactory.array();
for(JsonValue value : authors) values.add(value);
JsonObject result = JsonFactory.object().add("authorName", values);
return result.toCompactString()
You can use JSON-Java --> https://www.baeldung.com/java-org-json
Or the Google JSON, aka GSON and a few others as listed here --> https://javarevisited.blogspot.com/2016/09/top-5-json-library-in-java-JEE.html
To see popularity and use statistics, which might help you chose which ones to test first: https://www.baeldung.com/java-json
You can use GSON as it easily maps JSON with POJO classes (Especially nested ones)
For a quick reference for performance comparison,
I need to dynamically build the following post request JSON body with jmeter beanshell preprocessor. I am referring to the following question which has a solution for my problem with looped strings. I would need to do this with json-property(variables) an array of JSON objects with different name and values. Thanks a lot.
{
"processDefinitionId":"optaplannerkey:1:dbc4af8f-7e04-11e9-afa3-1ecac26bb5e0",
"businessKey":"optaplannerkey",
"returnVariables":true,
"variables": [
{
"name": "TaskDescription",
"value": "Fixing the issue with sink"
},
{
"name": "TaskCategory",
"value": "plumbing"
},
{
"name": "Priority",
"value": "Medium"
},
{
"name": "Status",
"value": "New"
},
{
"name": "SkillsRequired",
"value": "Plumbing Skills"
},
{
"name": "DueDate",
"value": "2019-05-24T11:23:08.030+05:30"
}
]
}
Use dummy sampler with the parameterized json request and CSV Data Set Config for the dynamic input. Below, I have paremeterized only two for demo.
Then, Use JSR223 Post processor with the following code:-
vars.put("responseVar",prev.getResponseDataAsString());
This will put response body in "responseVar" variable. Fetch it using ${responseVar}
Hope this helps.
I'm looking for a way I can create a custom formatting "rule/s" of some sort for pretty-printing JSON data. Currently, I'm using GSON to prettyprint, however, I'd like to output in a different format. To be more specific, I am trying to match the formatting of Minecraft JSON files.
Here's an example of GSON pretty-print:
[
{
"when": {
"OR": [
{
"conditional": false,
"facing": "north"
},
{
"conditional": false,
"facing": "north"
}
]
},
"apply": [
{
"model": "chain_command_block",
"weight": 1,
"uvlock": false,
"x": 0,
"y": 0
}
]
}
]
And here's an example of what I am trying to achieve:
[
{ "when": { "OR": [
{"conditional": false, "facing": "north"},
{"conditional": false, "facing": "north"}
]},
"apply": [
{ "model": "chain_command_block", "weight": 1, "uvlock": false, "x": 0, "y": 0 }
]
}
]
I think I'm going to have to manually format and output the data myself using a StringBuilder or a BufferedWriter but if anyone else has any other ideas, please let me know.
Any help is appreciated, thanks.
With GSON, you can register a typeAdapter and customise how a class should be serialised and deserialised.
https://futurestud.io/tutorials/gson-advanced-custom-serialization-part-1
EDIT: With this method, although you can define what data is used and how it's presented (in an array or a csv string etc...), I don't think you can actually change the structure of the pretty-printing.
For example, if I wanted to pretty-print an object, I also want to be able to define when to indent and when to move down to the next line for a certain class type. Still testing though so maybe I'm wrong,,,
Two days i spend to search efficent method to convert json string to url query string, for example
SRC:
"searchCriteria": {
"filterGroups": [
{
"filters": [
{
"field": "myfiled",
"value": "myvalue",
"conditionType": "eq"
}
]
}
],
"sortOrders": [
{
"field": "string",
"direction": "string"
}
],
"pageSize": 0,
"currentPage": 0
}
to:
http://host/api/?searchCriteria[filterGroups][][filters][][field]=myfield&searchCriteria[filterGroups][][filters][][value]=myvalue&searchCriteria[filterGroups][][filters][][conditionType]=eq&..
Some suggestions ?
A.
Thank U for answer, but ...
I've tryed to pass directly with payload json string and api give me an error, when I put instead query string like in my example, api respond in right way.
In PHP is very simple: json can be converted in array and so with function "http_build_query" it's done ! I'm suprised that not exist similar method .
Alb
I want to parse a json structure like this:
{"response":
{
"arr1":[count,{...}],
"arr2":[count,{...}]
}
}
Everything is ok if count have key "count" (for example). But the key is blank. Is it any way to map this structure and manually retrive only this value or i need to parse all of this json myself without gson ?
UPDATED
Here is a valid json (checked with http://jsonlint.com/)
{
"response": {
"arr1": [
615,
{
"body": "hi",
"title": "Re(2): ..."
},
{
"body": "hello",
"title": "Re(23): ..."
}
],
"arr2": [
132,
{
"body": "hi",
"title": "Re(2): ..."
},
{
"body": "hello",
"title": "Re(23): ..."
}
]
}
}
If you want to parse arbitrary collections you should read Serializing and Deserializing Collection with Objects of Arbitrary Types and look at the example code example code.