How to save data from textfields to json file? - java

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

Related

How to add subnode to json file using json-simple

I create json file with the folloing code:
import java.io.FileWriter;
import java.io.IOException;
import org.json.simple.JSONObject;
public class CreatingJSONDocument {
public static void main(String args[]) {
//Creating a JSONObject object
JSONObject jsonObject = new JSONObject();
//Inserting key-value pairs into the json object
jsonObject.put("ID", "1");
jsonObject.put("First_Name", "Shikhar");
try {
FileWriter file = new FileWriter("E:/output.json");
file.write(jsonObject.toJSONString());
file.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("JSON file created: "+jsonObject);
}
}
OUTPUT:
JSON file created: {
"First_Name":"Shikhar",
"ID":"1"}
How can I add content of java map to the this json output as a new node sothat I have at the end the following output:
JSON file created: {
"First_Name":"Shikhar",
"ID":"1",
"data": {
"a": "Test1",
"b": "Test2"
}
}
You just need to add another object of type JsonObject and it will do that
//...
jsonObject.put("ID", "1");
jsonObject.put("First_Name", "Shikhar");
jsonObject.put("data", new JSONObject(data));
//...
And that will return the output what you want
In case you need add more fields without a object a good practice its do the next:
JSONObject mainFields = new JSONObject();
mainFields.put("id", "1");
JSONObject secondFields = new JSONObject();
secondFields.put("field1", "some cool");
secondFields.put("field2", "not cool");
mainFields.put("data", secondFields);
This return:
{
"id":"1",
"data":{
"field1": "some cool",
"field2": "not cool"
}
}

Appending entry into JSON array with JSON-simple

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
}

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");

JSONObject in Android

Here i want to fetch the data from the json, but i am getting only first two objects value (25, 44) but the ids are 50,60 . I don't know whats wrong with this code.
Below is my response from the server:
{
"product": {
"25": {
"training": "First Name",
"taken": null,
"date": "1386737285",
"body":"http://abc.xyz.in/video1.mp4",
"image": "http://abc.xyz.in/video1.jpg"
},
"44": {
"training": "Second Name",
"taken": null,
"date": "1389951618",
"body":"http://abc.xyz.in/video2.mp4",
"image":"http://abc.xyz.in/video2.jpg"
},
"50": {
"training": "Third Name",
"taken": null,
"date": "1389971004",
"body":"http://abc.xyz.in/video3.mp4",
"image": "http://abc.xyz.in/video3.jpg"
},
"60": {
"training": "Fourth Name",
"taken": null,
"date": "1390003200",
"body": "http://abc.xyz.in/video4.mp4",
"image": "http://abc.xyz.in/video4.jpg"
}
}
}
Here is the code for fetching data from json:
public String[] getDataFromResponse(String jsonProfileResponse,String secondParam,
String attributeName ) {
String[] attributeValue = null;
try {
json = new JSONTokener(jsonProfileResponse).nextValue();
if (json instanceof JSONObject) {
JSONObject jsonObject = (JSONObject) json;
JSONObject jObj = jsonObject.getJSONObject(secondParam);
System.out.println(jObj);
Iterator<?> keys = jObj.keys();
List<String> listitems = new ArrayList<String>();
List<String> nids = new ArrayList<String>();
while (keys.hasNext()) {
nids.add(String.valueOf(keys.next()));
JSONObject jsonObj = jObj.getJSONObject(String.valueOf(keys
.next()));
System.out.println(jsonObj);
listitems.add(jsonObj.getString(attributeName));
}
attributeValue = listitems.toArray(new String[0]);
trainingId = nids.toArray(new String[0]);
}
} catch (JSONException ex) {
ex.printStackTrace();
}
return attributeValue;
}
Thanks for the considering...
Inside the hasNext you call twice keys.next()
So, instead of
nids.add(String.valueOf(keys.next()));
JSONObject jsonObj = jObj.getJSONObject(String.valueOf(keys.next()));
you have to do
String currentKey = String.valueOf(keys.next());
nids.add(currentKey);
JSONObject jsonObj = jObj.getJSONObject(currentKey);
String key="";
while (keys.hasNext()) {
key= keys.next()
JSONObject jsonObj = jObj.getJSONObject(String.valueOf(key));
nids.add(key));
System.out.println(jsonObj);
listitems.add(jsonObj.getString(attributeName));
}
use of key.next() twice is problem
because in JSONObject, the order of the keys is undefined.
#see: http://developer.android.com/reference/org/json/JSONObject.html#keys%28%29
try to sort your data on server, then response it in JSONArray

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