I want to create a JSON array structure like this or append an object to the structure
{ "user" : [
{"name" : "user1", "email": "user1#gmail"},
{"name": "user2", "email": "user2#gmail"}
]
}
I'm using GSON to write this into a file
public void appendToObject(File jsonFile, String key, String value) {
Objects.requireNonNull(jsonFile);
Objects.requireNonNull(key);
Objects.requireNonNull(value);
if (jsonFile.isDirectory()) {
throw new IllegalArgumentException("File can not be a directory!");
}
try {
JsonObject node = readOrCreateNew(jsonFile);
JsonArray userArray = new JsonArray();
userArray.add(user(key,value));
node.add("user", userArray);
FileWriter writer = new FileWriter(jsonFile)
gson.toJson(node, writer);
}catch (Exception e)
{
Log.d("display1", "appendToObject: error"+e.getLocalizedMessage());
e.printStackTrace();
}
}
private JsonObject user(String user, String password){
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("name", user);
jsonObject.addProperty("password", password);
return jsonObject;
}
private JsonObject readOrCreateNew(File jsonFile) throws IOException {
if (jsonFile.exists() && jsonFile.length() > 0) {
try (BufferedReader reader = new BufferedReader(new FileReader(jsonFile))) {
return gson.fromJson(reader, JsonObject.class);
}
}
return new JsonObject();
}
Here's the code with suggestions integrated and with reading and writing JSON file functions
but im getting "user1":"{\"values\":[null,\"user13\",\"useremail13\"]}"}
how to structure it so that I get the desired output
I omitted some your code in appendToObject. But the meaning should be clear.
public void appendToObject(File jsonFile, String key, String value) {
...
JsonObject node = readOrCreateNew(jsonFile);
JsonObject newUser = user(key, value);
JsonElement user = node.get("user");
if (user != null && user.isJsonArray()){
((JsonArray) user).add(newUser);
} else {
JsonObject root = new JsonObject();
node.add("user", createArray(newUser));
}
...
}
private JsonObject createUserArray(JsonObject ... objects){
JsonArray userArray = new JsonArray();
for (JsonObject user : objects) {
userArray.add(user);
}
return userArray;
}
private JsonObject user(String email, String name){
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("name", name);
jsonObject.addProperty("email", email);
return jsonObject;
}
I currently received the json file in java, turned the json file on the formun, debugged it, and tried sysout.
The problem is, I try to output to the table in jsp, but only the last source from json comes out.
How can we solve this?
#RequestMapping(value = "spaghettiSub", method = RequestMethod.POST)
public String spaghetti(ModelMap modelMap) {
JSONParser jsonParser = new JSONParser();
try{
JSONArray page = (JSONArray) jsonParser.parse(new FileReader("d:\\spaghetti.json"));
int pageCnt = page.size();
Map<String,String> map = new HashMap<String,String>();
List<Map<String,String>> spaghettiList = new ArrayList<Map<String,String>>();
for(int i = 0; i < pageCnt; i++) {
Object obj = page.get(i);
JSONObject jsonObject = (JSONObject) obj;
String no = (String) jsonObject.get("no");
String name = (String) jsonObject.get("name");
String explanation= (String) jsonObject.get("explanation");
map.put("no", no);
map.put("name", name);
map.put("explanation", explanation);
spaghettiList.add(map);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
return "sub/" + this.urlbase + "/spaghetti";
}
json
[
{
"no": "1",
"name": "Spaghettoni",
"explanation": "It is commonly used in the Carbonara Spaghetti, which is about 2mm thick."
},
{
"no": "2",
"name": "Spaghettini",
"explanation": "Spaghetti 1.6mm thick"
},
{
"no": "3",
"name": "Fedelini",
"explanation": "Spaghetti from 1.3mm to 1.5mm thick"
}]
you have to move this Map<String,String> map = new HashMap<String,String>(); inside your for loop.
Note:
As JB Nizet mentioned start using objects instead of JsonArray.
First thing first
Solve Issue
You are only getting last row in your JSP is because you have declared your Map outside of for loop.
If you are in hurry and have no time in world just move this
Map<String,String> map = new HashMap<String,String>();
inside
for(int i = 0; i < pageCnt; i++) {
This will solve your problem.
Improve your Code
But you can make it way more better and efficient by doing something like this
Define a DTO class
public class MyData {
private String no;
private String name;
private String explanation;
// getter setter
}
Use this DTO class to fill values like you did for Map
The whole code looks something like this.
#RequestMapping(value = "spaghettiSub", method = RequestMethod.POST)
public String spaghetti(ModelMap modelMap) {
JSONParser jsonParser = new JSONParser();
try{
JSONArray page = (JSONArray) jsonParser.parse(new FileReader("d:\\spaghetti.json"));
int pageCnt = page.size();
List<MyData> spaghettiList = new ArrayList<MyData>();
for(int i = 0; i < pageCnt; i++) {
MyData mydata = new MyData();
Object obj = page.get(i);
JSONObject jsonObject = (JSONObject) obj;
String no = (String) jsonObject.get("no");
String name = (String) jsonObject.get("name");
String explanation= (String) jsonObject.get("explanation");
mydata.setNo(no);
mydata.setName(name);
mydata.setExplanation(explanation);
spaghettiList.add(mydata);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
return "sub/" + this.urlbase + "/spaghetti";
}
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");
I try to learn Loop through a JSON object in Java for loop this case.But My json loop first array(ident AFL274) and stop not loop next array(CQH8971)(in json data have 2 arrays)I call this function by button.
this for call for json
public String getInfo(String url) {
try {
String result = HttpGet(url);
JSONObject json = new JSONObject(result);
JSONObject val = json.getJSONObject("SearchResult");
JSONArray data = val.getJSONArray("aircraft");
for(int i=0;i<data.length();i++)
{
JSONObject data1 = data.getJSONObject(i);
String ans = data1.getString("ident");
}
} catch (JSONException e) {
e.printStackTrace();
}
return ans;
}
and this JSON:
{
"SearchResult": {
"next_offset": -1,
"aircraft": [
{
"ident": "AFL274",
"type": "B77W"
},
{
"ident": "CQH8971",
"type": "A320"
}
]
}
}
Try this,
public String[] getInfo(String url) {
try {
String result = HttpGet(url);
JSONObject json = new JSONObject(result);
JSONObject val = json.getJSONObject("SearchResult");
JSONArray data = val.getJSONArray("aircraft");
int arrayLength = data.length();
String[] strAryAns = new String[arrayLength];
for(int i=0;i<arrayLength;i++)
{
JSONObject data1 = data.getJSONObject(i);
strAryAns[i] = data1.getString("ident");
}
} catch (JSONException e) {
e.printStackTrace();
}
return strAryAns;
}
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