Appending entry into JSON array with JSON-simple - java

I'm having trouble appending to a JSON file. I can add the new entry but not insert it into the correct position.
Code:
public static void main(String args[]) throws Exception {
{
File file = new File("jsonFormatting.json");
if (!file.exists()) {
System.out.println("No file");
} else {
try {
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("jsonFormatting.json"));
JSONObject jsonObject = (JSONObject) obj;
JSONArray jsonItemInfo = (JSONArray) jsonObject.get("itemInfo");
JSONObject newObject = new JSONObject();
newObject.put("item", new Integer(10003));
newObject.put("name", "ID10003");
StringWriter out = new StringWriter();
newObject.writeJSONString(out);
String jsonText = out.toString();
System.out.println(jsonText);
jsonItemInfo.add(newObject);
FileWriter fileToWrite = new FileWriter("jsonFormatting.json", true);
try {
fileToWrite.write(jsonItemInfo.toJSONString());
} catch (IOException e) {
e.printStackTrace();
}
fileToWrite.flush();
fileToWrite.close();
} catch (IOException | ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
JSON file:
"sampleArray": [
"Element_0",
"Element_1"
],
"dataPoint_1": 40,
"dataPoint_2": 500,
"dataPoint_3": 650,
"itemInfo": [
{
"item": "10001",
"name": "ID10001",
},
{
"item": "10002",
"name": "ID10002",
}
]
I would like to add the following into the "itemInfo":
{
"item": "10003",
"name": "ID10003",
}
However, when I run my Java code, it adds this to the end of the JSON file, rather than inserting the new entry following the original 2:
[{"item":"10001","name":"ID10001"},{"item":"10002","name":"ID10002"},{"item":10003,"name":"ID10003"}]
Thanks in advance for any advice you may offer!

I run this code and it is working fine can you test this stuff on your side. If i understand you question correct.
public static void main(String args[]) throws Exception {
{
File file = new File("jsonFormatting.json");
if (!file.exists()) {
System.out.println("No file");
} else {
try {
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("jsonFormatting.json"));
JSONObject jsonObject = (JSONObject) obj;
JSONArray jsonItemInfo = (JSONArray) jsonObject.get("itemInfo");
JSONObject newObject = new JSONObject();
newObject.put("item", new Integer(10003));
newObject.put("name", "ID10003");
StringWriter out = new StringWriter();
newObject.writeJSONString(out);
String jsonText = out.toString();
System.out.println(jsonText);
jsonItemInfo.add(newObject);
jsonObject.put("itemInfo", jsonItemInfo);
FileWriter fileToWrite = new FileWriter("jsonFormatting.json", false);
try {
fileToWrite.write(jsonObject.toJSONString());
} catch (IOException e) {
e.printStackTrace();
}
fileToWrite.flush();
fileToWrite.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
my jsonFormatting.json file data look like
{"sampleArray": [
"Element_0",
"Element_1"
],
"dataPoint_1": 40,
"dataPoint_2": 500,
"dataPoint_3": 650,
"itemInfo": [
{
"item": "10001",
"name": "ID10001"
},
{
"item": "10002",
"name": "ID10002"
}
]
}
and output is
{
"sampleArray": [
"Element_0",
"Element_1"
],
"itemInfo": [
{
"item": "10001",
"name": "ID10001"
},
{
"item": "10002",
"name": "ID10002"
},
{
"item": 10003,
"name": "ID10003"
}
],
"dataPoint_2": 500,
"dataPoint_1": 40,
"dataPoint_3": 650
}

Related

JSON flattener returning only last object from JSON to a flattened form

I have a JSON that looks like below,
{
"users": [
{
"displayName": "Sharad Dutta",
"givenName": "",
"surname": "",
"extension_user_type": "user",
"identities": [
{
"signInType": "emailAddress",
"issuerAssignedId": "kkr007#gmail.com"
}
],
"extension_timezone": "VET",
"extension_locale": "en-GB",
"extension_tenant": "EG12345"
},
{
"displayName": "Sharad Dutta",
"givenName": "",
"surname": "",
"extension_user_type": "user",
"identities": [
{
"signInType": "emailAddress",
"issuerAssignedId": "kkr007#gmail.com"
}
],
"extension_timezone": "VET",
"extension_locale": "en-GB",
"extension_tenant": "EG12345"
}
]
}
I have the above code and it is able to flatten the JSON like this,
{
"extension_timezone": "VET",
"extension_tenant": "EG12345",
"extension_locale": "en-GB",
"signInType": "userName",
"displayName": "Wayne Rooney",
"surname": "Rooney",
"givenName": "Wayne",
"issuerAssignedId": "pdhongade007",
"extension_user_type": "user"
}
But the code is returning only the last user in the "users" array of JSON. It is not returning the first user (essentially the last user only, no matter how many users are there) just the last one is coming out in flattened form from the "users" array.
public class TestConvertor {
static String userJsonAsString;
public static void main(String[] args) throws JSONException {
String userJsonFile = "C:\\Users\\Administrator\\Desktop\\jsonRes\\json_format_user_data_input_file.json";
try {
userJsonAsString = readFileAsAString(userJsonFile);
} catch (Exception e1) {
e1.printStackTrace();
}
JSONObject object = new JSONObject(userJsonAsString); // this is your input
Map<String, Object> flatKeyValue = new HashMap<String, Object>();
System.out.println("flatKeyValue : " + flatKeyValue);
readValues(object, flatKeyValue);
System.out.println(new JSONObject(flatKeyValue)); // this is flat
}
static void readValues(JSONObject object, Map<String, Object> json) throws JSONException {
for (Iterator it = object.keys(); it.hasNext(); ) {
String key = (String) it.next();
Object next = object.get(key);
readValue(json, key, next);
}
}
static void readValue(Map<String, Object> json, String key, Object next) throws JSONException {
if (next instanceof JSONArray) {
JSONArray array = (JSONArray) next;
for (int i = 0; i < array.length(); ++i) {
readValue(json, key, array.opt(i));
}
} else if (next instanceof JSONObject) {
readValues((JSONObject) next, json);
} else {
json.put(key, next);
}
}
private static String readFileAsAString(String inputJsonFile) throws Exception {
return new String(Files.readAllBytes(Paths.get(inputJsonFile)));
}
}
Please suggest where I am doing wrong or my code needs modification.
Please try the below approach, this will give you a comma separated format for both user and identifier (flat file per se),
public static void main(String[] args) throws JSONException, ParseException {
String userJsonFile = "path to your JSON";
final StringBuilder sBuild = new StringBuilder();
final StringBuilder sBuild2 = new StringBuilder();
try {
String userJsonAsString = convert your JSON to string and store in var;
} catch (Exception e1) {
e1.printStackTrace();
}
JSONParser jsonParser = new JSONParser();
JSONObject output = (JSONObject) jsonParser.parse(userJsonAsString);
try {
JSONArray docs = (JSONArray) output.get("users");
Iterator<Object> iterator = docs.iterator();
while (iterator.hasNext()) {
JSONObject userEleObj = (JSONObject)iterator.next();
JSONArray nestedIdArray = (JSONArray) userEleObj.get("identities");
Iterator<Object> nestIter = nestedIdArray.iterator();
while (nestIter.hasNext()) {
JSONObject identityEleObj = (JSONObject)nestIter.next();
identityEleObj.keySet().stream().forEach(key -> sBuild2.append(identityEleObj.get(key) + ","));
userEleObj.keySet().stream().forEach(key -> {
if (StringUtils.equals((CharSequence) key, "identities")) {
sBuild.append(sBuild2.toString());
sBuild2.replace(0, sBuild2.length(), "");
} else {
sBuild.append(userEleObj.get(key) + ",");
}
});
}
sBuild.replace(sBuild.lastIndexOf(","), sBuild.length(), "\n");
}
System.out.println(sBuild);
} catch (Exception e) {
e.printStackTrace();
}
}

How to save data from textfields to json file?

how to save data from our textfields. For example i want to get this:
[
{
"Patient": {
"name": "John",
"surname": "Cena"
}
},
{
"Patient2": {
"name": "Roger",
"surname": "Federer"
}
}
]
And it was my try:
JSONObject obj = new JSONObject();
obj.put("imie", field1.getText());
obj.put("nazwisko", field2.getText());
try (FileWriter Data = new FileWriter("Data.JSON")) {
Data.write(obj.toJSONString());
Data.write(obj1.toJSONString());
} catch (IOException e1) {
e1.printStackTrace();
}
but i dont get "Patient2" and it overwriting my first patient if i press save button instead of add new one.
You should be using JSONArray to store several JSONObject instances:
// build object
JSONObject obj = new JSONObject();
obj.put("name", field1.getText());
obj.put("surname", field2.getText());
// build "patient"
JSONObject patient = new JSONObject();
patient.put("patient", obj);
// build another object
JSONObject obj1 = new JSONObject();
obj1.put("name", "Roger");
obj1.put("surname", "Federer");
// build another patient
JSONObject patient1 = new JSONObject();
patient1.put("patient1", obj1);
// create array and add both patients
JSONArray arr = new JSONArray();
arr.put(patient);
arr.put(patient1);
try (FileWriter Data = new FileWriter("Data.JSON")) {
Data.write(arr.toString(4)); // setting spaces for indent
} catch (IOException e1) {
e1.printStackTrace();
}
This code produces JSON:
[
{
"patient": {
"surname": "Doe",
"name": "John"
}
},
{
"patient1": {
"surname": "Federer",
"name": "Roger"
}
}
]

Read JSON Object from an Array using Simple JSON Jar

I have a JSON file as below
{
"ClassId": "1",
"ClassName": "mobiles",
"ClassItems": [
{
"ItemId": "1",
"ItemName": "Nokia",
"ItemImageName": "nokia.jpg",
"ItemUnitPrice": "200.00",
"ItemDiscountPercent": "0"
},
{
"ItemId": "2",
"ItemName": "Samsung",
"ItemImageName": "samsung.jpg",
"ItemUnitPrice": "400.00",
"ItemDiscountPercent": "0"
}
]
}
I am trying to access the ItemIds for all the items with ClassId=1. I am able to print the complete json array but I am not able to find print itemIds alone.
The java code I use is below:
public class JSONExample {
/**
* #param args the command line arguments
* #throws java.io.IOException
*/
public static void main(String[] args) throws IOException {
JSONParser parser=new JSONParser();
try {
Object obj=parser.parse(new FileReader("JSON/TestJson.json"));
JSONObject jsonObject=(JSONObject) obj;
String classId=(String) jsonObject.get("ClassId");
String className=(String) jsonObject.get("ClassName");
if(classId.equals("1")){
JSONArray itemList = (JSONArray) jsonObject.get( "ClassItems" );
Iterator iterator=itemList.iterator();
while(iterator.hasNext())
{
System.out.println(itemList.get(1));
iterator.next();
}
}
} catch (FileNotFoundException ex) {
Logger.getLogger(JSONExample.class.getName()).log(Level.SEVERE, null, ex);
} catch (ParseException ex) {
Logger.getLogger(JSONExample.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
String itemId;
for (int i = 0; i < itemList.length(); i++) {
JSONObject obj= itemList.getJSONObject(i);
itemId=(String) jsonObject.get("ItemId");
}
Try the above instead of iterator.
Note: if you're using(importing) org.json.simple.JSONArray, you have to use JSONArray.size() to get the data you want. But use JSONArray.length() if you're using org.json.JSONArray.

How do I access this JSON Array in Java?

This is what I have, but the number of children never prints out. I'm getting the raw JSON, then making a JSONArray, accessing the second member's children. What am I missing here? I have similar code that works perfectly, only difference is in the JSON, it does not start with an array
JSON Input:
[
{
"kind":"Listing",
"data":{
"modhash":"",
"children":[
{
"kind":"t3",
"data":{
"domain":"",
"banned_by":null,
"media_embed":{
},
"subreddit":"",
"selftext_html":"",
"selftext":"",
"likes":null,
"secure_media":null,
"link_flair_text":null,
"id":"1zeek5",
"secure_media_embed":{},
"clicked":false,
"stickied":false,
"author":"xVictoryy",
"media":null,
"score":1,
"approved_by":null,
"over_18":false,
"hidden":false,
"thumbnail":"",
"subreddit_id":"t5_2sdpm",
"edited":false,
"link_flair_css_class":null,
"author_flair_css_class":null,
"downs":0,
"saved":false,
"is_self":true,
"permalink":"",
"name":"t3_1zeek5",
"created":1393843471.0,
"url":"",
"author_flair_text":null,
"title":"Seeking advice.",
"created_utc":1393814671.0,
"ups":1,
"num_comments":3,
"visited":false,
"num_reports":null,
"distinguished":null
}
}
],
"after":null,
"before":null
}
},
{
"kind":"Listing",
"data":{
"modhash":"",
"children":[
{
"kind":"t1",
"data":{
"subreddit_id":"t5_2sdpm",
"banned_by":null,
"subreddit":"",
"likes":null,
"replies":{
"kind":"Listing",
"data":{
"modhash":"",
"children":[
{
"kind":"t1",
"data":{
"subreddit_id":"t5_2sdpm",
"banned_by":null,
"subreddit":"cscareerquestions",
"likes":null,
"replies":"",
"saved":false,
"id":"cfsxjqn",
"gilded":0,
"author":"xVictoryy",
"parent_id":"t1_cfsx26m",
"approved_by":null,
"body":"",
"edited":false,
"author_flair_css_class":null,
"downs":0,
"body_html":"",
"link_id":"t3_1zeek5",
"score_hidden":false,
"name":"t1_cfsxjqn",
"created":1393845230.0,
"author_flair_text":null,
"created_utc":1393816430.0,
"distinguished":null,
"num_reports":null,
"ups":1
}
}
],
"after":null,
"before":null
}
},
"saved":false,
"id":"cfsx26m",
"gilded":0,
"author":"dauphic",
"parent_id":"t3_1zeek5",
"approved_by":null,
"body":"A lot of schools don't expect high school Calculus.",
"edited":false,
"author_flair_css_class":"",
"downs":0,
"body_html":"",
"link_id":"t3_1zeek5",
"score_hidden":false,
"name":"t1_cfsx26m",
"created":1393844079.0,
"author_flair_text":"Software Engineer",
"created_utc":1393815279.0,
"distinguished":null,
"num_reports":null,
"ups":1
}
},
{
"kind":"t1",
"data":{
"subreddit_id":"t5_2sdpm",
"banned_by":null,
"subreddit":"cscareerquestions",
"likes":null,
"replies":"",
"saved":false,
"id":"cft3lbj",
"gilded":0,
"author":"I_EAT_GUSHERS",
"parent_id":"t3_1zeek5",
"approved_by":null,
"body":"",
"edited":false,
"author_flair_css_class":"",
"downs":0,
"body_html":"",
"link_id":"t3_1zeek5",
"score_hidden":false,
"name":"t1_cft3lbj",
"created":1393864015.0,
"author_flair_text":"Looking for internship",
"created_utc":1393835215.0,
"distinguished":null,
"num_reports":null,
"ups":1
}
}
],
"after":null,
"before":null
}
}
]
My code:
List<Comment> fetchComments() {
Log.d("running", "attempting fetch...");
String raw = RemoteData.readContents(url);
List<Comment> list = new ArrayList<Comment>();
try {
JSONObject data = new JSONArray(raw).getJSONObject(1);
JSONArray children = data.getJSONArray("children");
Log.d("running", "comments: " + children.length());
}
} catch (Exception e) {
Log.e("fetchComments()", e.toString());
}
return list;
}
public static String readContents(String url){
HttpURLConnection hcon=getConnection(url);
if(hcon==null) return null;
try{
StringBuffer sb=new StringBuffer(8192);
String tmp="";
BufferedReader br=new BufferedReader(
new InputStreamReader(
hcon.getInputStream()
)
);
while((tmp=br.readLine())!=null)
sb.append(tmp).append("\n");
br.close();
return sb.toString();
}catch(IOException e){
Log.d("READ FAILED", e.toString());
return null;
}
}
You didn't get into data object... You only have "kind" and "data" tags in your list items, so first get into "data" tag then get "children". Try like this:
List<Comment> fetchComments() {
Log.d("running", "attempting fetch...");
String raw = RemoteData.readContents(url);
List<Comment> list = new ArrayList<Comment>();
try {
JSONObject data = new JSONArray(raw).getJSONObject(1);
JSONArray children = data.getJSONObject("data").getJSONArray("children");
Log.d("running", "comments: " + children.length());
}
} catch (Exception e) {
Log.e("fetchComments()", e.toString());
}
return list;
}
Your JSON array contains objects that have a field "data" that contains an object that contains a field "children".
You're doing:
JSONObject data = new JSONArray(raw).getJSONObject(1);
JSONArray children = data.getJSONArray("children");
You missed the data field.
JSONObject obj = new JSONArray(raw).getJSONObject(1);
JSONArray children = obj.getJSONObject("data").getJSONArray("children");

Parse multiple items in JSON into an array

I have a client that retrieves some json from this page. The json content looks like this:
{
"0": {
"name": "McDonalds 2",
"address": "892 West 75th Street, Naperville, IL 60540"
},
"1": {
"name": "McDonalds 1",
"address": "1298 South Naper Boulevard, Naperville, IL 60540"
},
"2": {
"name": "Burger King 1",
"address": "2040 Aurora Avenue, Naperville, IL, 60540"
}
}
I'm having problems parsing it. I always get an exception when trying to parse anything. It's my first time doing json so I might be doing something really bad. This is my code:
public static void parse(String jsonData)
{
JSONObject jsonObject = new JSONObject();
try
{
jsonObject = new JSONObject(jsonData);
}
catch (JSONException e)
{
e.printStackTrace();
}
try
{
// exception happens here when trying to access data
JSONObject name = ((JSONArray)jsonObject.get("0")).getJSONObject(0)
.getJSONObject("name");
JSONObject address = ((JSONArray)jsonObject.get("0")).getJSONObject(0)
.getJSONObject("address");
} catch (JSONException e) {}
}
How an I retrieve the name and address of each json item to convert it into a restaurant object?
The format of the JSON is wrong. Please refer to this link and the right code is below. You will know what to do.
public static void parse(String jsonData) {
ArrayList<Restaurant> restaurantList= new ArrayList<Restaurant>();
JSONObject jsonObject;
JSONObject jsonRestaurant;
try {
jsonObject= new JSONObject(jsonData);
for(int i=0;i<3;i++) {
Restaurant restaurant= new Restaurant();
jsonRestaurant= jsonObject.getJSONObject(Integer.toString(i));
restaurant.name= jsonRestaurant.getString("name");
restaurant.address= jsonRestaurant.getString("address");
restaurantList.add(restaurant);
}
}
catch(JSONException e) {
e.printStackTrace();
}
}

Categories