I have a .json file that contains JSON data. I created this file by simply Ctrl + C and Ctrl + V (from server output) Here's part of my file
[{
"ID": "109",
"objectTypeID": "1",
"names": [{
"ID": 1,
"code": "lt",
"value": "Trak\u0173 salos pilis "
}, {
"ID": 2,
"code": "en",
"value": "Trakai Island Castle"
}, {
"ID": 3,
"code": "ru",
"value": "\u0422\u0440\u0430\u043a\u0430\u0439\u0441\u043a\u0438\u0439 \u0437\u0430\u043c\u043e\u043a"
}, {
"ID": 4,
"code": "de",
"value": "Kasteel van Trakai"
}],
"descriptions": [{
"ID": 1,
"code": "lt",
"value": "<div><strong>Paslap\u010di\u0173 m\u0117g\u0117jams ir ieškotojams<\/strong><\/div>\r\n\r\n<div>Tiems, kurie domisi istorija, kurie m\u0117gsta paslaptingas vietoves, \u012f Trakus atkeliauti b\u016btina. Trak\u0173 pilis yra vienas labiausiai turist\u0173 lankom\u0173 objekt\u0173 Lietuvoje......"
}]
}]
I have saved this file with utf-8 encoding
As you can see there are lot of Unicode Characters and html elements like <div>, <strong> and so on....
Now I want to parse this file. Here's my java/android code
private String getJSONString(File file){
try {
FileInputStream is = new FileInputStream(file.getAbsolutePath());
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
return new String(buffer, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private void object_parser(File file){
String jsonString = getJSONString(file);
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(jsonString);
Log.d("OBJECTS_LIST_AAA", jsonArray.toString());
} catch (JSONException e) {
Log.d("OBJECTS_LIST_ERROR", e.getMessage()); // print error
e.printStackTrace();
}
}
}
and I get this error Unterminated object at character 5641 of [{"ID":"109","objectTypeID":"1","names":[{"ID":1,"code":"lt","value":"Trak\u0173 salos pilis "},......
I think that formating is missing in this file.
Your Every "Restaurant "Avilys"" like data are invalid, You have to replace all of them with "Restaurant Avilys" as a single String value quoted with only two quotation marks. There are many similar cases like these as well. And note that the part you posted is clearly valid and can be parsed easily, Here is no such errors.
Related
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.
data.json , please note dup key city
{
"type": "1",
"city": [
{
"name": "c1",
"dis": [
{
"dis_name": "d1"
},
{
"dis_name": "d2"
}
]
}
],
"city": [
{
"name": "c2",
"dis": [
{
"dis_name": "d3"
},
{
"dis_name": "d2"
}
]
}
]
}
I think, because of dup key, JSON object built from the file is incorrect or has partial data.
JSONObject obj = new JSONObject(readJSONFromAsset());
readJSONFromAsset() copied from stackoverflow,
public String readJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("data.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
return json;
}
in obj, I see only partial data of json file. What is the best way to add following new entry in json file/object?
"city": [
{
"name": "c3",
"dis": [
{
"dis_name": "d5"
},
{
"dis_name": "d2"
}
]
}
]
That's not a valid json document. Valid json cannot have duplicate keys. What happens when you try to treat it as JSON depends on how your deserializer chooses to implement it- it could throw an exception, keep the first, or keep the last as common choices.
The only answer which will work is to fix your data so it is a valid json document. I'd suggest turning city into an array.
Today I started writing a simple parser for a log file. I want to take the log file and transform it into a simple json structure.
The log file is consistent and has 3 main parts (example below):
the timestamp [23 digits]
the code [4 digits]
the payload [variable digits]
Example log
2018-07-25T08:47:16,094,164f,test1
2018-07-25T08:47:18,163,1678,test2
2018-07-25T08:47:19,501,1662,test3
2018-07-25T08:47:21,278,1634,test4
2018-07-25T08:47:23,347,1632,test5
2018-07-25T08:47:24,686,1665,test6
2018-07-25T08:47:26,463,1678,test7
2018-07-25T08:47:28,533,1678,test8
2018-07-25T08:47:29,877,1632,test9
2018-07-25T08:47:31,687,1632,test10
From this I wanted to create a JSON file that would incorporate well the information inside. This is what I came up with (using org.json.JSONObject library).
BufferedReader reader = new BufferedReader(new FileReader ("file.log"));
String line = null;
String timestamp = null;
String eventCode = null;
String payload = null;
JSONObject codePayload = new JSONObject();
JSONObject finalString = new JSONObject();
for (int i = 0; i < 10; i++) {
line = reader.readLine();
timestamp = line.substring(0, 23);
eventCode = line.substring(24, 28);
payload = line.substring(29, line.length());
codePayload.put("ID", eventCode);
codePayload.put("PL", payload);
finalString.put(timestamp, codePayload);
codePayload = new JSONObject();
}
System.out.println(finalString.toString());
This little snippet should work quite well (don't mind the for) and it kinda does. It creates the JSON file according to the string I give it but it puts then in a strange order, see below.
{
"2018-07-25T08:47:24,686": {
"ID": "1665",
"PL": "test6"
},
"2018-07-25T08:47:29,877": {
"ID": "1632",
"PL": "test9"
},
"2018-07-25T08:47:31,687": {
"ID": "1632",
"PL": "test10"
},
"2018-07-25T08:47:16,094": {
"ID": "164f",
"PL": "test1"
},
"2018-07-25T08:47:21,278": {
"ID": "1634",
"PL": "test4"
},
"2018-07-25T08:47:18,163": {
"ID": "1678",
"PL": "test2"
},
"2018-07-25T08:47:23,347": {
"ID": "1632",
"PL": "test5"
},
"2018-07-25T08:47:28,533": {
"ID": "1678",
"PL": "test8"
},
"2018-07-25T08:47:19,501": {
"ID": "1662",
"PL": "test3"
},
"2018-07-25T08:47:26,463": {
"ID": "1678",
"PL": "test7"
}
}
As you can clearly see it places the objects in the wrong order and I really don't know why. If someone has the slightest idea on how this problem could occur please comment below. Thanks a lot!
The org.json.JSONObject is un-ordered, so better to use javax.json.JSONObject OR if you are using org.json library, use the org.json.JSONArray to store the timestamps in order.
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.
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.