how to convert json into json string with spacing preserved? - json

I want to convert Json into Json String like below in Spring-Boot application. How to do this? Thanks in advance.
{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
}
Convert the above as:
"{\"userId\":1,\"id\":1,\"title\":\"delectusautautem\",\"completed\":false}"
Here i am converting json String to JsonNode but not getting desired result.
ObjectMapper mapper = new ObjectMapper();
String json = json_view.toString();
JsonNode processed_json = mapper.readTree(json);

I read the above json into jsonNode and convert again to json String .
ObjectMapper objectMapper= new ObjectMapper();
String json = """
{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
}
""";
JsonNode jsonNode= objectMapper.readTree(json);
String jsonConverted= objectMapper.writeValueAsString(jsonNode);
System.out.println(jsonConverted);
and ouput will be
{"userId":1,"id":1,"title":"delectus aut autem","completed":false}

Related

Can't convert JSON to object

Json response looks like this:
{
"status": 1,
"data": [
[
{
"id": "4iQDR9r1Ch",
"body": "test test",
"da": "1601575850",
"dm": "1601575850"
}
]
]
}
And my classes:
data class NotesListResponse(
#SerializedName("status") val status: Int,
#SerializedName("data") val data: List<List<NoteResponse>>)
data class NoteResponse(
#SerializedName("id") val id: String,
#SerializedName("body") val body: String,
#SerializedName("da") val da: String,
#SerializedName("dm") val dm: String
)
Error message: com.google.gson.stream.MalformedJsonException: Unterminated object at line 1 column 48 path $.data[0][0].body
What's wrong? JSON is valid and classes were checked for correctness
Try the following if you have access to the Gson class. The lenient mode may allow you to see if it works and there are characters that the non-lenient mode can't parse.
Gson gson = new Gson();
JsonReader reader = new JsonReader(new StringReader(<insert response>));
reader.setLenient(true);

JSON Array Parsing Kafka

I have the following setup:
A Rest endpoint to accept JSON POST request:
I am parsing the request and sending it as a String over Kafka.
But getting parsing errors
A Rest endpoint to accept JSON POST request:
[ { "Name": "Jack", "Id": "314", "Gender": "M" } , { "Name": "John", "Id": "451", "Gender": "M" }, { "Name": "Rita", "Id": "501", "Gender": "F" } ]
I am parsing the request as follows
#RequestMapping(method = RequestMethod.POST, value = "/record")
#ResponseBody
public String process(#RequestBody Map<String, Object>[] payload) throws
Exception {
String str = Arrays.toString(payload)
KafkaProd.toTopic(str);
System.out.println("Payload: " +str);
return "Record Processed";
}
str = Arrays.toString(payload) is changing it into the following format
[ { Name = Jack , Id = 314, Gender = M } , { Name = John, Id = 451,
Gender = M }, { Name = Rita, Id = 501, Gender = F } ]
When I'm trying to parse this string back into json array using json-s
imple :
JSONArray jsonArray = new JSONArray(record.value());
for (int i = 0; i < jsonArray.length(); i++) {
System.out.println("Json Objects : "
+jsonArray.getJSONObject(i).toString());
}
I am getting JSON Parsing error, since the record.value() is not a valid json array
Option 1. How do I convert this to a valid json array?
Option 2. How do I send the json array in a proper format through kafka?
Which of these options do I use?
Instead of String str = Arrays.toString(payload) use a Jackson ObjectMapper to convert the map to a String.

String is not parsing in JSONSerializer

i have a json string like
{"id":0,"version":0,"subject":"[2sravya] data","description":"[10nd data] description [AWS Account:12234]","createdDate":null,"visibleToCustomer":false,"externalEMailId":null}
After it is converted to JSONObject using JSONSerializer.toJSON() the JSONObject contains value like
{
"id": 0,
"version": 0,
"subject": "[2sravya] fdaya",
"description": [
"10nd data"
]
}
data present in description is a string data. i want the same to be present in formatted JSONObject.

How to create a JSON structure for this

Can you tell me how to create a Json objecct for this
I think it is a JSON with children JSON objects.
[{
"data": {
"ID": "56e819a90111257894be41c9e310f8cb",
"name": "Email_____2016-03-15 10_18_16",
"objCode": "DOCU",
"description": null,
"lastUpdateDate": "2016-03-15T10:18:17:551-0400"
}
}: null]
I did this
JSONObject childVal = new JSONObject();
JSONObject parent = new JSONObject();
try {
childVal.put("ID", "56e819a90111257894be41c9e310f8cb");
childVal.put("name", "Email_____2016-03-15 10_18_16");
childVal.put("objCode", "DOCU");
childVal.put("description", "null");
childVal.put("lastUpdateDate", "2016-03-15T10:18:17:551-0400");
parent.put("data", childVal);
but how do i get the parent [ object : null]
thanks

GSON deserialize as array although JSON source is object

I'd like to deserialize this using GSON into a list of Post, but can't figure out how to tell GSON how to ignore the root element "posts" (as its an object) and just process the array.
I've got:
Type postTypeList = new TypeToken<List<Post>>(){}.getType();
JsonParser jsonParser = new JsonParser();
JsonElement jsonElement = jsonParser.parse(myJSONString);
JsonObject postsRootObj = jsonElement.getAsJsonObject();
List<Post> postList = gson.fromJson(postsRootObj.get("posts"), postTypeList);
BUT.. I'd rather not have the whole JsonParser, I'd rather just pass it directly into the gson.fromJson function.. Is there a way to do this?
{ "posts":
[
{
"username": "John",
"message": "I'm back",
"time": "2010-5-6 7:00:34"
"validator":[{
"prog": "Name1",
"name": "Name2",
"computername": "Name3",
"date": "2010-11-20 19:39:55"
}]
}
,
{
"username": "Smith",
"message": "I've been waiting",
"time": "2010-4-6 10:30:26"
"validator":[{
"prog": "Name1",
"name": "Name2",
"computername": "Name3",
"date": "2010-11-20 19:39:55"
}]
}
]}
Create a wrapper class which will have List<Post> as its member
public class PostList{
private List<Post> posts;
// getter and setters for posts
}
And then use fromJson in the similar fashion
List<Post> postList = gson.fromJson(myJSONString,PostList.class);
There is a correction from above. Usage should be :
PostList postList = gson.fromJson(myJSONString,PostList.class);
Post post = postlist.get(index) //index is the index of list you want to access