Custom PrintFormatting for GSON - java

I'm having some trouble with GSON in regards to printing. GSON has two options when it comes to printing.
Pretty Printing
Compact Printing
I intend to use a modified form of Pretty Printing and even though the documentation says JsonPrintFormatter is the class which is used to modify the output format. I can't find that class in the GSON repository!
Any ideas on why this is the case or anyway I can modify the GSON printing?
Apart from that, any libraries used to modify spacing or formatting of JSON in the Java language would also be helpful.
Pretty Print:
{
"classname": "something",
"type": "object",
"version": 1,
"properties": [
{
"propertyname": "something1",
"type": "String",
"length": 255
},
{
"propertyname": "something2",
"type": "Date",
"length": 10
}
]
}
Compact Print:
{"classname":"something","type":"object","version":1,"properties":[{"propertyname":"something1","type":"String","length":255},{"propertyname":"something2","type":"Date","length":10}]}
My Print Style:
{
"classname": "something",
"type": "object",
"version": 1,
"properties": [
{"propertyname": "something1","type": "String","length": 255},
{"propertyname": "something2","type": "Date","length": 10}
]
}

Well, it's just work in progress for now, but this should do the trick for strings with only one array. Will look into to making it more stable and able to handle more complex structures.
private static String reformat(String og){
String reformattable = og;
String[] parts = reformattable.split("\\[",2);
String arrayPart = parts[1];
String arrayOnly = arrayPart.split("]",2)[0];
reformattable = arrayOnly.replaceAll("\\{\n","{");
reformattable = reformattable.replaceAll("\",\n", "\\\",");
reformattable = reformattable.replaceAll(" +"," ");
reformattable = reformattable.replaceAll("\\{ "," {");
reformattable = reformattable.replaceAll("\n }","}");
return og.replace(arrayOnly,reformattable);
}
Result should look like this (at least for my simple class):
{
"classname": "test",
"properties": [
{"propertyname": "1", "length": 1},
{"propertyname": "1", "length": 1}
]
}

Related

How to count particular pattern in a string?

we have some requests which have a lot of experiments. I just want to count the no experiments. If it's greater than some number then I will block those requests
{
"context": {
"requestId": "",
"locale": "",
"deviceId": "",
"currency": "",
"memberId": 0,
"cmsOrigin":,
"experiments": {
"forceByVariant":,
"forceByExperiment": [
{
"id": "test",
"variant": "A"
}
]
}
}
In this request, I just want to check how many id and variant inside the forceByExperiment. I have tried to do using regular expression but not able to do it. Anyone do it before similar thing.
I just split the string with variant and count them. Not sure good idea, but the end goal is to figure out that the request have a lot of experiments.
Using the circe library and Scala, here is an easy solution:
import io.circe._, io.circe.parser._
val jsonString = """{
"context": {
"requestId": "",
"locale": "",
"deviceId": "",
"currency": "",
"memberId": 0,
"cmsOrigin": "foo",
"experiments": {
"forceByVariant": [],
"forceByExperiment": [
{
"id": "test",
"variant": "A"
}
]
}
}
}"""
val parseResult = parse(jsonString)
val nElems = for {
json <- parse(jsonString)
array <- json.hcursor.downField("context").downField("experiments").downField("forceByExperiment").as[Seq[Json]]
} yield array.length
println(nElems) // Right(1)
If you really want to use regex, and if there is no id field in your json structure, you can use the following expression "id": "(\w+)" and count the number of match.
Example: https://regex101.com/r/GCeByw/1/

Jackson/Gson get specified key from Json - Java

i have problem with get specified value from json. I need get Key value from json below, its start with array/list.
[
{
"Version": 1,
"Key": "353333_PC",
"Type": "PostalCode",
"Rank": 500,
"LocalizedName": "Suwalki",
"EnglishName": "Suwalki",
"PrimaryPostalCode": "16-400",
"Region": {
"ID": "EUR",
"LocalizedName": "Europe",
"EnglishName": "Europe"
},
"Country": {
"ID": "PL",
"LocalizedName": "Poland",
"EnglishName": "Poland"
}
}
]
I have tried code like this:
String content = parent.path("Key").asText();
return content;
but it returns empty string. Have u any idea how get this?

Parse json response of rest API and delete certain jsonObjects - JAVA

I have a json file as below which I am getting as a response from rest API:
{
"label": " MARA LEYZIN",
"ClassCode": "PROFESSIONAL",
"actvFlg": "A",
"name": "MARA LEYZIN",
"Typ": {
"label": "C_TYP_LU",
"TypCode": "PROFESSIONAL "
},
"Address": {
"link": [],
"firstRecord": 1,
"pageSize": 10,
"searchToken": "multi",
"item": [
{
"label": "Address",
"addrTypFk": {
"label": "C_ADDRESS_TYPE_LU",
"addrTypCd": "INDUSTRY",
"addrTypDesc": "Industry"
}
}
]
}
I am trying to parse this in Java and to remove some unwanted json objects. Like I want the following string to be replaced by blank:
"link": [],
"firstRecord": 1,
"pageSize": 10,
"searchToken": "multi",
"item":
To achieve this I am trying the following approach:
String jsonStr = new String(Files.readAllBytes(Paths.get(inputFile)));
System.out.println(jsonStr);
jsonStr.replaceAll("link", "");
But it is not replacing the required string with blanks. Please help me in this.
string object is immutable , so basically if do you want to replace something
System.out.println(jsonStr.replaceAll("link", "")); this will print the replaced string but it will not affect the original string, however if you do this
jsonStr=jsonStr.replaceAll("link", "");
System.out.println(jsonStr); this will print the replaced string
First of all:
Your JSON is not validate. You're missing a closing curly bracket at the end of it.
{
"label": " MARA LEYZIN",
"ClassCode": "PROFESSIONAL",
"actvFlg": "A",
"name": "MARA LEYZIN",
"Typ": {
"label": "C_TYP_LU",
"TypCode": "PROFESSIONAL "
},
"Address": {
"link": [],
"firstRecord": 1,
"pageSize": 10,
"searchToken": "multi",
"item": [{
"label": "Address",
"addrTypFk": {
"label": "C_ADDRESS_TYPE_LU",
"addrTypCd": "INDUSTRY",
"addrTypDesc": "Industry"
}
}]
}
}
Second of all you should just change order of your commands to this:
jsonStr.replaceAll("link", "");
System.out.println(jsonStr);
Important addition:
And I would suggest you to use org.json library or even better JACKSON to parse JSON files.
Here's tutorial how to use jackson and it's my warmest suggestion.
You will save a lot of time and you can do whatever you like.

JSON Array Of Entries to POJO

I have a JSON file that has multiple entries inside of an array. Each of those entries needs to be mapped to a java object. Here is the JSON string I am testing with (http://jsonlint.com/ validated the JSON below, but I had to erase all of the escape characters which I use in the actual Java test),
[{
"LocId":99,
"typeId":99,
"name":"foo",
"parentId":99,
"geoCode":
{
"type":"foo",
"coordinates":
[{
"latitude":99.0,
"longitude":99.0
}]
}
,
"LocId":8,
"typeId":99,
"name":"foo",
"parentId":99,
"geoCode":
{
"type":"foo",
"coordinates":
[{
"latitude":99.0,
"longitude":99.0
}]
}
}]
I read this string in like this,
String str = "The JSON string shown above";
InputStream is = new ByteArrayInputStream(str.getBytes());
BufferedReader br = new BufferedReader(new InputStreamReader(is));
LocIdClass[] locations = new Gson().fromJson(br, LocIdClass[].class);
But the size of my locations array is always one and only the last entry in the JSON string is stored.
for(int i=0; i<locations.length; i++)
System.out.println(locations[i]);
System.out.println("The size of the array is " + locations.length);
I'm not sure why only the last entry in the JSON string would be retrieved but the others are skipped. I referred to this SO post to figure out the POJO array Jackson - Json to POJO With Multiple Entries.
you have an error in your current json payload, try this:
[
{
"LocId": 99,
"typeId": 99,
"name": "foo",
"parentId": 99,
"geoCode": {
"type": "foo",
"coordinates": [
{
"latitude": 99,
"longitude": 99
}
]
}
},
{
"LocId": 8,
"typeId": 99,
"name": "foo",
"parentId": 99,
"geoCode": {
"type": "foo",
"coordinates": [
{
"latitude": 99,
"longitude": 99
}
]
}
}
]
Edit: To avoid this issue in the future, you can use jsonlint.com to check your json. Make sure it is what you expect it to be.

Aws Json Exception - A JSONObject text must begin with '{' at 1 [character 2 line 1]

I am facing an error with json , although
System.out.println((int)text.trim().charAt(0));
returns 123 which means it does starts with curly bracket.
I am totally out of ideas and i also tried to trim() instead of toString().
InputStream bis = new ByteArrayInputStream(bytes);
InputStream is = new GZIPInputStream(bis);
byte[] unPackedBytes = IOUtils.toByteArray(is);
String text = new String(unPackedBytes, "UTF-8");
JSONObject obj = new JSONObject(text.toString());
It is so weird because when i input the json it doesn't give any errors but when i give the compressed file it does gives errors but the output of the compressed file is exactly same with json, so i am confused.
This is the Json.
{
"id": 123,
"providerId": 123,
"externalTrackId": "068d",
"genres": [
{
"genre": "Rap/Hip-Hop",
"subGenre": "Rap/Hip-Hop"
}
],
"title": {
"title": "The "
},
"artists": [
{
"name": {
"primary": {
"value": "J-"
}
},
"role": "Artist"
}
],
"contributors": [],
"release": {
"id": 123,
"title": {
"title": "The "
},
"artist": {
"primary": {
"value": "J"
}
},
"externalId": "gener2cec9477d",
"genre": {
"genre": "Rap/Hip-Hop",
"subGenre": "Rap/Hip-Hop"
},
"copyrightYear": 0
},
"trackCountInMedia": 0,
"mediaCountInRelease": 0,
"signature": {
"url": "https:",
"id": 123,
"type": "FULL",
"audioType": "MUSIC",
"creation": "2013-"
},
"label": "Unknown",
"lastMod": "2013-01-04T16:02:57.607Z"
}
Cheers
I found my answer , it was a mistake of me because i wasn't decoding data from Base64.
It's weird because it was seemed like exactly same output but it wasn't.
Thanks to #Jhanvi for trying to help me.

Categories