How do I remove all control characters in a string in Java? - java

My REST API, which is build with Spring in Java, produces an invalid JSON object, because it contains multiple breaks in a string, which lead to the problem, that the string has an unexpected end and the rest doesn't count as part of the string anymore, example:
{
"status": "Success",
"message": "Lorem ipsum",
"data": {
"correct": [
{
"record": "ULTRA LONG
XML STRING
WITH BREAKS",
"code": 0,
"errors": []
}
]
}
}
The error arises in the data -> correct -> record string field, because it contains breaks which splits the original string.
My API endpoint serializes the above JSON like this:
#PostMapping(value="/check-records",
consumes=MediaType.APPLICATION_JSON_VALUE,
produces=MediaType.APPLICATION_JSON_VALUE)
public Response checkRecords(#RequestBody(required=true) Records records) {
// Check records
return new Response("Success", "Lorem ipsum", data);
}
Response is a class, which automatically gets serialized into a JSON object after returning. data is a map in order to create the above JSON structure.
I couldn't find any suitable solution for my problem yet. Does anybody has an idea how I could remove all breaks, spaces or control characters before I serialize the JSON object?
I appreciate any kind of help, sheers! :)

Thanks to #pringi. He suggested to use a regex to remove all control characters in Java before I serialize the JSON object.
String record = orginalRecord.replaceAll("[\\\\p{Cntrl}^\\r\\n\\t]+", "")
You can find more informations about regex in the original question: How to remove control characters from java string?

Related

Using JsonPath to parse JSON String recursively

I'm trying to parse a given JSON in String format, for example:
{
"id": "indeed",
"interaction_data":
"{\"data\":\"{\\\"something\\\":\\\"blabla\\\"}\",\"somethingElseNotNested\":\"Indeed\"}"
}
I'm working with Kotlin, and I called JsonPath.parse on the value above, the problem is, interaction_data is parsed as a String, instead of it being treated as a JSON as well.
So when I call read("$.interaction_data.data.something") it gives me an error, since interaction_data is treated as a String, instead of an object.
Any way around this? (other than parsing this part separately, I need to handle this generically).
Thanks!
Json interaction_data property is triple stringifyied. Why you don't try this
var jsonObject=..your json;
var jsonParsed=JSON.parse(jsonObject.interaction_data);
jsonParsed.data=JSON.parse(jsonParsed.data);
JsonObject.interaction_data=jsonParsed;
result
{
"id":"indeed",
"interaction_data":{"data"{"something":"blabla"},"somethingElseNotNested":"Indeed"}
}

Filter JSON string from String having json string and normal string in java

I am stuck in a problem where I have to filter json data from a String which is a combination of json string and normal text.
sample: This message has all your required detail { "name" : "xyz","age": "21","place" :"sdf", "number": "7689"} check in this page you will get the details.
I need to extract the json object from given string.
Result expected is only : { "name" : "xyz","age": "21","place" :"sdf", "number": "7689"}.
Is there any clean way of doing this in Java.
One way to solve this is to remove non-json string and extract json object.
But that is a bad approach in my view.
If there are no other JSON-like parts, you can just extract the part between the first { and last }, including both ends:
int start=str.indexOf('{');
int end=str.lastIndexOf('}');
String json=str.substring(start,end+1);
Then of course you may want to check if both start and end are non-negative (so the characters are actually present), if there is a possibility that the string does not contain anything for you.
Also note that JSON can be an array too, so you can try checking if a pair of first [ and last ] lies outside of the {...}, but then at the end single values are valid JSON too (like true, false, 1, etc.). This is not really a happy task to write properly, thinking of everything.

Java: Escape html entity in json string

Sorry for my english. My question:
Using jsoup i get json response from site. Some entities have unescaped html charactes, for example
{
"status":200,
"result":[
{
"id":22,
"title":"<p>Мир "Юрского периода" искусств</p>",
"view":1153039,
"image":{
"desktop":{
"image":"img.png",
"svg":"img.svg"
}
},
"part":{
"topic":" Глава\Глава"
}
}
],
"message":""
}
I use Gson. If i try to deserialize this string i will get error on double quotes in title and "\" in topic.
How Can i escape these characters. I only know one way to do this: using regex get string in topic and title and change " to \".
The only problem is that there are many such json entity, and it takes a lot of time. Is there a better way?

Parse json arrays with ValidatableResponseOptions.body

As ValidatableResponseOptions.body documentation shows you can "parse" a JSON to check whether a value exists (or similar).
Now my JSON liiks like this:
[
{
"from_name": "Peter",
},
{
"from_name": "Max"
}
]
I want to check if there are arrays with the from_name Peter. I tried:
.body("[].from_email", equalTo("Peter"))
This throws the error Invalid JSON expression:Script1.groovy: 1: unexpected token: [ # line 1, column 27. [].from_email ^1 error.
Trying following also not works:
.body("$..from_email", equalTo(shopEmailAddress))
or
.body(".from_email", equalTo(shopEmailAddress))
How is the correct syntax for this?
You've tried to parse an array of json instead of a json. That's what the error is telling you. You should iterate on the array and parse each json independently.
You can also stream the array and look for the first case which verifies your predicate.

Parse a JSON string in Java

I would like to know how I can access the data from the below JSON String.
{
"posters": {
"thumbnail": "http://google.com/images/11420914_ori.jpg",
"profile": "http://google.com/images/11420914_ori.jpg"
}
}
I want this to be done in Java Lists (NOT by using JSON Parsers)
Expected output:
thumbnail: "http://google.com/images/11420914_ori.jpg"
profile: "http://google.com/images/11420914_ori.jpg"
You need a Json Mapper, I recommend you to read this : Jackson in 5 minutes

Categories

Resources