Add new entry to the json file which has dup key - java

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.

Related

Json data parse into table in java transformation in informatica developer

I have data in below format-
{
"result": [
{
"number": "C12",
"name": "ABC"
},
{
"number": "D12",
"name": "BCD"
},
{
"number": "E56",
"name": "fm"
}]
}
My code is -
String result = //that store my above json data;
try{
String jsonString = result;
JSONObject obj = new JSONObject(jsonString);
JSONArray arr = obj.getJSONArray("result");
for (int i = 0; i < arr.length(); i++)
{
String num = arr.getJSONObject(i).getString("number");
String name= arr.getJSONObject(i).getString("name");
generateRow();
}
}
catch(Exception e)
{
e.printStackTrace();
}
But with this code i am able to read only first record.
Please help in writing the code where i can read all the records.
You can move to Informatica developer tool in case you have the license and use H2R transformation

JSON to JSON Transform of input sample using any existing java library/tools

Input:
{
"Student": {
"name" :"abc",
"id" : 588,
"class : "12"
}
}
Reqired Output:
{
"Student": {
"key" :"name",
"value":"abc",
"key" :"id",
"value":"588",
"key" :"class",
"value":"12"
}
}
Your output json invalid. Json object can not duplicate key .
You can use the library org.json and do something like this:
JSONObject jsonObject = new JSONObject(inputJson);
JSONObject outputJson = new JSONObject();
JSONArray array = new JSONArray();
for (Object key : jsonObject.keySet()) {
JSONObject item = new JSONObject();
String keyStr = (String)key;
Object keyvalue = jsonObj.get(keyStr);
item.put(keyStr, keyvalue);
array.put(item);
}
outputJson.put("Student", array);
System.out.println(json.toString());
Output :
{
"Student": [
{
"key": "name",
"value": "abc"
},
{
"key": "id",
"value": "588"
},
{
"key": "class",
"value": "12"
}
]
}
Similar to the other answer, the desired output JSON format is not valid.
The closest valid output would be
{
"Student" : [ {
"key" : "name",
"value" : "abc"
}, {
"key" : "id",
"value" : 588
}, {
"key" : "class",
"value" : "12"
} ]
}
This can be generated via Jolt with the following spec
[
{
"operation": "shift",
"spec": {
"Student": {
"name": {
"$": "Student[0].key",
"#": "Student[0].value"
},
"id": {
"$": "Student[1].key",
"#": "Student[1].value"
},
"class": {
"$": "Student[2].key",
"#": "Student[2].value"
}
}
}
}
]
This is easy to solve with JSLT if we assume the output is made valid JSON by making an array of key/value objects like the other respondents do.
The array function converts an object into an array of key/value objects exactly like you ask for, so the transform becomes:
{"Student" : array(.Student)}

Json data parsing and display in List using Codename one

Here I have to parse JSON data getting from Facebook and display in list using Codename one so how can I cast ArrayList with Map.
Here is my Json data
{
"posts": {
"data": [
{
"story": "Gaurav Takte shared a link.",
"created_time": "2017-02-14T19:08:34+0000",
"id": "1323317604429735_1307213186040177"
},
{
"story": "Gaurav Takte shared a link.",
"created_time": "2017-02-02T14:22:50+0000",
"id": "1323317604429735_1295671703860992"
},
{
"message": "Hurray....... INDIA WON KABBADI WORLD CUP 2016",
"created_time": "2016-10-22T15:55:04+0000",
"id": "1323317604429735_1182204335207730"
},
{
"story": "Gaurav Takte updated his profile picture.",
"created_time": "2016-10-21T05:35:21+0000",
"id": "1323317604429735_1180682575359906"
},
{
"message": "Friends like all of you … I would love to keep forever.
#oldmemories with # besties
#happydays",
"story": "Gaurav Takte with Avi Bhalerao and 5 others.",
"created_time": "2016-10-21T05:33:55+0000",
"id": "1323317604429735_1180682248693272"
},
{
"message": "\"सर्वांना गणेशचतुर्थीच्या हार्दीक शुभेच्छा.
तुमच्या मनातील सर्व मनोकामना पूर्ण होवोत , सर्वांना
सुख, समृध्दी, ऎश्वर्य,शांती,आरोग्य लाभो हीच
बाप्पाच्या चरणी प्रार्थना. \"
गणपती बाप्पा मोरया , मंगलमुर्ती मोरया !!!",
"story": "Gaurav Takte with Avi Bhalerao and 18 others.",
"created_time": "2016-09-05T05:06:58+0000",
"id": "1323317604429735_1133207030107461"
}
]
}
}
So how can I parse it and also display in list manner in Codename one.
Check out the JSONParser class in Codename One which the developer guide covers.
The sample from the guide is pasted below but I suggest reading it there as it is properly annotated there:
Form hi = new Form("JSON Parsing", new BoxLayout(BoxLayout.Y_AXIS));
JSONParser json = new JSONParser();
try(Reader r = new InputStreamReader(Display.getInstance().getResourceAsStream(getClass(), "/anapioficeandfire.json"), "UTF-8")) {
Map<String, Object> data = json.parseJSON(r);
java.util.List<Map<String, Object>> content = (java.util.List<Map<String, Object>>)data.get("root");
for(Map<String, Object> obj : content) {
String url = (String)obj.get("url");
String name = (String)obj.get("name");
java.util.List<String> titles = (java.util.List<String>)obj.get("titles");
if(name == null || name.length() == 0) {
java.util.List<String> aliases = (java.util.List<String>)obj.get("aliases");
if(aliases != null && aliases.size() > 0) {
name = aliases.get(0);
}
}
MultiButton mb = new MultiButton(name);
if(titles != null && titles.size() > 0) {
mb.setTextLine2(titles.get(0));
}
mb.addActionListener((e) -> Display.getInstance().execute(url));
hi.add(mb);
}
} catch(IOException err) {
Log.e(err);
}
hi.show();
Try this,
JSONObject obj=new JSONObject(response);
JSONObject posts_obj=obj.getJSONObject("posts");
JSONArray data_arr=posts_obj.getJSONArray("data");
for(int i=0;i<data_arr.length();i++) {
JSONObject data_obj=data_arr.getJSONObject(i);
String story = data_obj.getString("story");
String created_time = data_obj.getString("created_time");
String id = data_obj.getString("id");
if(data_obj.has("message")) {
String message = data_obj.getString("message");
}
}

JSON Unterminated object at character android

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.

Get sub-array from JSON

I parsing some data from a json file. Here is my JSON File.
[
{
"topic": "Example1",
"contact": [
{
"ref": [
1
],
"corresponding": true,
"name": "XYZ"
},
{
"ref": [
1
],
"name": "ZXY"
},
{
"ref": [
1
],
"name": "ABC"
},
{
"ref": [
1,
2
],
"name":"BCA"
}
] ,
"type": "Presentation"
},
{
"topic": "Example2",
"contact": [
{
"ref": [
1
],
"corresponding": true,
"name": "XYZ"
},
{
"ref": [
1
],
"name": "ZXY"
},
{
"ref": [
1
],
"name": "ABC"
},
{
"ref": [
1,
2
],
"name":"BCA"
}
] ,
"type": "Poster"
}
]
I can fetch and store data one by one. Like this one
JSONArray getContactsArray = new JSONArray(jsonObject.getString("contact"));
for(int a =0 ; a < getContactsArray.length(); a++)
{
JSONObject getJSonObj = (JSONObject)getContactsArray.get(a);
String Name = getJSonObj.getString("name");
}
1)Now, my question is there any way to get all name values for each array with single query.
2) Can I get all those values in an Array ?
Please correct me, if I am doing anything wrong. Thank you.
Iteration cannot be avoided here as org.json and other Json parsers as well provide random access to objects but not to their properties collectively (as a collection). So, you can't query something like "all name properties of all contact objects" unless you probably get a Json parser like Gson to unmarshall it that way.
But, that's too much to just avoid a for loop when you can definitely shorten the parse by making use of the appropriate API methods to avoid unnecessary object casts.
JSONArray contacts = jsonObject.getJSONArray("contact");
String[] contactNames = new String[contacts.length()];
for(int i = 0 ; i < contactNames.length; i++) {
contactNames[i] = contacts.getJSONObject(i).getString("name");
}
Better to use a json parser such as GSon or Jackson to marshall your json to a java object. Then you can write utitlity method in your java class to retrieve all the names in that object.
Try this:
Create JSONObject of your file and try to get array of all names and iterate it to get all values.
public static String[] getNames(JSONObject jo) {
int length = jo.length();
if (length == 0) {
return null;
}
Iterator i = jo.keys();
String[] names = new String[length];
int j = 0;
while (i.hasNext()) {
names[j] = (String) i.next();
j += 1;
}
return names;
}

Categories