How do I access this JSON Array in Java? - 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");

Related

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

Parsing arrays in Json using Gson

Parsing arrays in json using Gson.
I have this following json and trying to parse it.
{
"success": true,
"message": "success message",
"data": [
{
"city": "cityname",
"state": "statename",
"pin": 0,
"name" :{
"firstname" : "user"
},
"id" :"emailid"
}],
"status" : "done"
}
So, I have created pojo classes using http://www.jsonschema2pojo.org/
Now, I want to parse the array, for value "city".This is how I did but not sure what is wrong here.
Gson gson = new Gson();
Records obj = gson.fromJson(response,Records.class);
try {
JSONArray jsonArray = new JSONArray(obj.getData());
for(int i=0; i<jsonArray.length(); i++)
{
JSONObject object = jsonArray.getJSONObject(i);
String city = object.getString("city");
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setMessage(city);
dialog.show();
}}
catch (Exception e) {
e.printStackTrace();
}
And this is what getData() is defined in model class:
public class Records {
//////
private ArrayList<Datum> data = null;
public ArrayList<Datum> getData() {
return data;
}
this is not required:
try {
JSONArray jsonArray = new JSONArray(obj.getData());
...
}
catch
...
you just need to do
Records obj = gson.fromJson(response,Records.class);
and then
obj.getData();
would be great if you check that getData() is not null, beacuse something xould go wrong when deserialising
for getting the city: use the getter in the Datum class, you have at the end a list of those obejcts when you call getData
public String getCity() {
return city;
}

Output a JSON string with previous Format in JAVA

I have this JSON flat file and I need to change the value of clientCode
{
"clientNumber": "Test",
"clientCode": "12345",
"clientReference": "JSON Testing",
"billingCode":"90code",
"clienttructure": "new, test, Java",
"site": "sampleStore",
"siteDestination": "EU",
}
I tried to change clientCode value and check the return of the method.
I'm Using Java
String jsonName = "clientCode ";
String jsonValue = "new Value";
String JSONSource = path;
public String put(String jsonName, String jsonValue, String JSONSource) {
String jsonString = null;
try {
Object obj = parser.parse(new FileReader(JSONSource));
org.json.simple.JSONObject jsonObject = (org.json.simple.JSONObject) obj;
jsonObject.put(jsonName, jsonValue);
jsonString = jsonObject.toJSONString();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
return jsonString;
}
Actual output is:
{ "billingCode":"90code", "clientCode": "new Value","clientNumber": "Test","clientReference": "JSON Testing",.....}
Expected output should be :
{
"clientNumber": "Test",
"clientCode": "new Value",
"clientReference": "JSON Testing",
"billingCode":"90code",
"clienttructure": "new, test, Java",
"site": "sampleStore",
"siteDestination": "EU",
}
Try this...
JSONObject jsonobject = new JSONObject(response);
jsonobject .remove("clientCode");
JSONObject updateValue = new JSONObject(updateValue);
String UpdatedValue = updateValue.getString("clientCode");
jsonobject .put("clientCode", UpdatedValue);

Android - Save JSON from InputStream into String

I'm trying to parse this JSON I get from a HttpURLConnection in Android.
{
"responsejson":
{
"value1": [
{
"data": "Call",
"label": "Call",
"default": false
},
{
"data": "Email",
"label": "Email",
"default": false
}
],
"value2": [
{
"attributes": {
"type": "Status",
"url": "/..."
},
"IsOpened": false,
"IsDefault": true,
"TechLabel": "NotStarted",
"Id": "01Jb"
},
{
"attributes": {
"type": "Status",
"url": "/..."
},
"IsOpened": false,
"IsDefault": false,
"TechLabel": "InProgress",
"Id": "01Jb"
},
{
"attributes": {
"type": "Status",
"url": "/..."
},
"IsOpened": true,
"IsDefault": false,
"TechLabel": "Completed",
"Id": "01Jb"
}
],
...
}
}
What I want to do is save the content of value1 in a string, the content of value2 in another string,... because I need to store it in the database, so in the future I can load and parse it. I am using JsonReader but it's not possible to do this with JsonReader.
// ...
inputStream = conn.getInputStream();
JsonReader json = new JsonReader(new InputStreamReader(in));
json.beginObject();
while (json.hasNext()) {
String valueName = json.nextName();
// String content = ?????
}
json.endObject();
// ...
Any ideas? Custom objects are not possible due to we never know which values the JSON is going to show.
Use this to convert JSON array to string
private String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the
* BufferedReader.readLine() method. We iterate until the
* BufferedReader return null which means there's no more data to
* read. Each line will appended to a StringBuilder and returned as
* String.
*/
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
Use Gson to parse the JSON that you receive in InputStream. Then you can get the ArrayList from that parsed object. Again, use Gson to serialize the arraylist back to JSON.
This code works for your example json.
public class Value1 {
public String data,label;
#SerializedName("default")
public boolean isdefault;
}
public class Value2 {
public Attributes attributes;
public boolean IsOpened,IsDefault;
public String TechLabel,Id;
}
public class Attributes {
public String type,url;
}
String jsonString = "{\"responsejson\":{\"value1\":[{\"data\":\"Call\",\"label\":\"Call\",\"default\":false},{\"data\":\"Email\",\"label\":\"Email\",\"default\":false}],\"value2\":[{\"attributes\":{\"type\":\"Status\",\"url\":\"/...\"},\"IsOpened\":false,\"IsDefault\":true,\"TechLabel\":\"NotStarted\",\"Id\":\"01Jb\"},{\"attributes\":{\"type\":\"Status\",\"url\":\"/...\"},\"IsOpened\":false,\"IsDefault\":false,\"TechLabel\":\"InProgress\",\"Id\":\"01Jb\"},{\"attributes\":{\"type\":\"Status\",\"url\":\"/...\"},\"IsOpened\":true,\"IsDefault\":false,\"TechLabel\":\"Completed\",\"Id\":\"01Jb\"}]}}";
try {
org.json.JSONObject object = new JSONObject(jsonString);
jsonString = object.getString("responsejson");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JsonParser parser = new JsonParser();
JsonObject obj = parser.parse(jsonString).getAsJsonObject();
List<Value1> list1 = new Gson().fromJson(obj.get("value1"), new TypeToken<List<Value1>>() {}.getType());
List<Value2> list2 = new Gson().fromJson(obj.get("value2"), new TypeToken<List<Value2>>() {}.getType());
Since you do not know json structure beforehand, your best bet is to use GSON 2.0 feature that supports default maps and lists.
Use the following code to deserialize :
Object object = new Gson().fromJson(jsonString, Object.class);
The created object is a Map (com.google.gson.internal.LinkedTreeMap) which looks like this (for the above example)
{responsejson={value1=[{data=Call, label=Call, default=false}, {data=Email, label=Email, default=false}], value2=[{attributes={type=Status, url=/...}, IsOpened=false, IsDefault=true, TechLabel=NotStarted, Id=01Jb}, {attributes={type=Status, url=/...}, IsOpened=false, IsDefault=false, TechLabel=InProgress, Id=01Jb}, {attributes={type=Status, url=/...}, IsOpened=true, IsDefault=false, TechLabel=Completed, Id=01Jb}]}}
Use the generated object, parse it and save it in your db.
You can serialize that map back to JSON using :
String json = new Gson().toJson(object);
Hope this helps you.
just read the stream regularly and save it into a regular String, then parse that String :
// to get the general object that contains all the values
JSONObject json = new JSONObject(json_readed);
JSONObject response = json.getJSONObject("responsejson");
// to get the values
List<JSONArray> all_values = new ArrayList<JSONArray>();
Iterator<?> keys = response.keys();
while( keys.hasNext() ){
String value = (String)keys.next();
if( response.get(value) instanceof JSONArray ){
all_values.add(response.getJSONArray(value));
}
}
now you have all the values(whatever what's it's name id) combined into that ArrayList called(all_values).
Note that the JSON you provided in your question is missing opening"{" and closing"}" brackets in the beginning and the ending of it.
What you need to do is, first create a JsonObject from the json string representation, at this stage no specifics are given.
JSONObject object = new JSONObject("json_here"); //catch all exceptions thrown.
Interestingly you mentioned that the structure varies, it consider that weird, i am guessing you are pulling from different api instances. What you need to do , create a pojo class mapping the api instance name to the returned json string body.
After you attained the Object of interest, consider using GSON. A Java serialization/deserialization library to convert Java Objects into JSON and back. What you then need to do is to,serialize the pojo class,into an object.Then store into the database. I recommend using realm and not SQLite.
Example serializing the class.
class JClass {
private String jType;
private String json_body;
JClass() {
// no-args constructor
}
}
JClass j = new JClass();
j.jType ="some_type";
j.json_body = "json_body_here";
Gson gson = new Gson();
String json = gson.toJson(j);
then get the json String object, and store in database of choice.
/*
* Method to parse InputStream to String JSON
* */
private String parse(InputStream in){
StringBuilder result;
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
Log.d("JSON Parser", "result: " + result.toString());
return result.toString();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
JSONParser parser = new JSONParser();
List<String> output = new ArrayList<String>();
try {
Object obj = parser.parse(data); // data is JSON
JSONObject jsonObject = (JSONObject) obj;
JSONArray msg = (JSONArray) jsonObject.get("value1");
JSONArray msg2 = (JSONArray) jsonObject.get("value2");
Iterator<String> iterator = msg.iterator();
while (iterator.hasNext()) {
output.add(iterator.next());
}
String[] stringArray = output.toArray(new String[0]);
return stringArray;
} catch (Exception e) {
return null;
}

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