JSON Array Of Entries to POJO - java

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.

Related

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?

Want to read JSONArray with JSONObject, but got the error A non-empty JSON Pointer

My Json FILE (it´s an array! )
[
{
"datasetid": "country-flags",
"recordid": "d661d0a8676bf4d7563114c1d9c465987df22132",
"fields": {
"num_un": 32,
"geolocation": [
-38.416097,
-63.616672
],
"dialing_code": "54",
"a3_un": "ARG",
"country": "Argentina",
"flag": {
"mimetype": "image/png",
"format": "PNG",
"filename": "ar.png",
"width": 16,
"id": "fceb4235ce95c8597bfa77d0db0181a0",
"height": 11,
"thumbnail": true
},
"a2_iso": "AR"
},
"geometry": {
"type": "Point",
"coordinates": [
-63.616672,
-38.416097
]
},
"record_timestamp": "2016-09-26T07:48:38.162+02:00"
},
more...
]
So i want to get the value from coordinates. So for this i tried to work with this:
JsonReader jsonReader = Json
.createReader(new FileReader(getClass().getResource("country-flags.json").getPath()));
JsonArray arr = jsonReader.readArray();
for(int i = 1; i<arr.size();i++)
{
JsonObject obj = arr.getJsonObject(i);
System.out.println("coordinates: " + obj.containsKey("\"coordinates\""));
System.out.println("##########");
System.out.println(obj.getValue("\"coordinates\""));
}
But i got the error:
javax.json.JsonException: A non-empty JSON Pointer must begin with a
'/'
Can someone help me out ?!
Your code obj.containsKey("\"coordinates\"") will return false as coordinates is NOT a top level key, but is a 2nd level (nested) key. If you print obj.keySet(), you will get [datasetid, recordid, fields, geometry, record_timestamp] (first / top level keys only).
If the structure of your JSON is fixed, you can use the following code:
for(int i = 1; i<arr.size();i++)
{
JsonObject obj = arr.getJsonObject(i);
JsonObject jsonChildObject = obj.getJsonObject("geometry");
if(jsonChildObject.containsKey("coordinates"))
System.out.println(jsonChildObject.getValue("/coordinates"));
}
Notice the / in front of the getValue method's coordinates param. I think that was the reason you were here in the first place.

Custom PrintFormatting for GSON

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}
]
}

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.

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