i'm trying to parse this below json format such as:
[
[
{
"mobileNumber":"<Censored>","contactUserId":"17",
"userEwallets":
[
{"accountNumber":"<Censored>"},
{"accountNumber":"<Censored>"},
{"accountNumber":"<Censored>"}
]
}
]
,
[
{
"mobileNumber":"<Censored>","contactUserId":"1",
"userEwallets":
[
{"accountNumber":"<Censored>"}
]
}
]
]
for parsing second json array of that as
[
{
"mobileNumber":"<Censored>",
"contactUserId":"1",
"userEwallets":
[
{"accountNumber":"<Censored>"}
]
}
]
i get this error:
Index 1 out of range [0..1)
from below code my code can only parse the first array of that, for second array i get exception when i try to get mobileNumber of second json array object
for (int i = 0; i < response.length(); i++) {
try {
JSONArray jsonArray = response.getJSONArray(i);
final String mobileNumber = jsonArray.getJSONObject(i).getString("mobileNumber");
final String contactUserId = jsonArray.getJSONObject(i).getString("contactUserId");
final String userEwallets = jsonArray.getJSONObject(i).getString("userEwallets");
Log.e("MobileNumber ", mobileNumber);
JSONArray ewallets = new JSONArray(userEwallets);
for (int j = 0; j < ewallets.length(); j++) {
JSONObject ewalletObject = ewallets.getJSONObject(j);
final String accountNumber = ewalletObject.getString("accountNumber");
Log.e("accountNumber ", accountNumber);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Try this one...
JSONArray response;
try {
response = new JSONArray(res);
for (int i = 0; i < response.length(); i++) {
JSONArray insideJSONArray = response.getJSONArray(i);
JSONObject jsonObject = insideJSONArray.getJSONObject(0);
String mobileNumber = jsonObject.getString("mobileNumber");
Log.e("TAG", "mobileNumber: " + mobileNumber);
String contactUserId = jsonObject.getString("contactUserId");
Log.e("TAG", "mobileNumber: " + contactUserId);
JSONArray userEwallets = jsonObject.getJSONArray("userEwallets");
for (int j = 0; j < userEwallets.length(); j++) {
JSONObject ewalletObject = userEwallets.getJSONObject(j);
final String accountNumber = ewalletObject.getString("accountNumber");
Log.e("accountNumber ", accountNumber);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Change:
final String mobileNumber = jsonArray.getJSONObject(i).getString("mobileNumber");
final String contactUserId = jsonArray.getJSONObject(i).getString("contactUserId");
final String userEwallets = jsonArray.getJSONObject(i).getString("userEwallets");
to
final String mobileNumber = jsonArray.getJSONObject(0).getString("mobileNumber");
final String contactUserId = jsonArray.getJSONObject(0).getString("contactUserId");
final String userEwallets = jsonArray.getJSONObject(0).getString("userEwallets");
Related
I am getting null pointer error while converting string to json object i have tried gson,parser etc but none seems to be working.
Can somebody provide a solution for below response (I have done substring in order to remove "data: "):
data: {
"C": "abc",
"A": [{
"B": "BcastHub",
"C": "onData",
"D": [{
"ID": "1",
"One": [{
"Plus": 5.0,
"Minus": 93400.0
}, {
"Plus": 4.9,
"Minus": 8570.0
}, {
"Plus": 4.8,
"Minus": 140606.0
}],
"Two": [{
"Plus": 5.1,
"Minus": 34.0
}, {
"Plus": 5.2,
"Minus": 44622.0
}, {
"Plus": 5.3,
"Minus": 2408.0
}]
}]
}]
}
My code for Fetching
try{
URL urlData = new URL(url);
BufferedReader reader = new BufferedReader(new InputStreamReader(
urlData.openConnection().getInputStream(), "utf-8"));
String struct = reader.readLine();
while ((struct = reader.readLine()) != null ) {
if(!struct.equals("")) {
struct = struct.substring(6,struct.length());
JSONParser parser = new JSONParser();
JSONObject lev1 =(JSONObject) parser.parse(struct);
//JSONObject lev1 = (JSONObject) obj;
JSONObject parent = (JSONObject) lev1.get("A");
for(int j=0;j<parent.length();j++) {
JSONObject child1 = (JSONObject) parent.get("D");
JSONArray child2 = (JSONArray) child1.get("One");
for (int i = 0; i < child2.length(); i++) {
JSONObject item = child2.getJSONObject(i);
final String plus = item.getString("Plus");
final String minus = item.getString("Minus");
runOnUiThread(new Runnable() {
#Override
public void run() {
tv.setText("Plus => " + plus + "Minus = > " + minus);
}
});
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
Tell me if you want anything else. Thanks.
Edit : I am trimming the start of the string in order to make it in proper format and then converting the string to JSONObject is giving me error. at JSONObject parent = (JSONObject) lev1.get("A"); as lev1 is null.
try {
jsonResponse = new JSONObject(strJson2);
JSONObject user = jsonResponse.getJSONObject("data");
num = user.getString("C");
JSONArray user1 = user.getJSONArray("A");
for (int i = 0; i < user1.length(); i++) {
jsonChildNode = user1.getJSONObject(i);
String B = jsonChildNode.getString("B");
String c2 = jsonChildNode.getString("C");
Toast.makeText(this, B + "::" + c2.toString(), Toast.LENGTH_SHORT).show();
JSONArray jsonArraysunject = jsonChildNode.getJSONArray("D");
for (int j = 0; j < jsonArraysunject.length(); j++) {
JSONObject DD = jsonArraysunject.getJSONObject(j);
String dd = DD.getString("ID");
Toast.makeText(this, dd.toString(), Toast.LENGTH_SHORT).show();
One = DD.getJSONArray("One");
for (int k = 0; k < One.length(); k++) {
// for (int i = 0; i < lengthJsonArr; i++) {
jsonChildNodeo = One.getJSONObject(k);
type = jsonChildNodeo.getString("Plus");
num = jsonChildNodeo.getString("Minus");
makeText.add("Plus - " + type);
makeText.add("Minus - " + num);
Toast.makeText(this, makeText.toString(), Toast.LENGTH_SHORT).show();
}
Toast.makeText(this, "hdjeh", Toast.LENGTH_SHORT).show();
Two = jsonChildNodeo.getJSONArray("Two");
Toast.makeText(this, Two.toString(), Toast.LENGTH_SHORT).show();
for (int r = 0; r < Two.length(); r++) {
JSONObject tw = Two.getJSONObject(r);
String tplus = tw.getString("Plus");
String tminus = tw.getString("Minus");
makeText2.add("plus - " + tplus);
makeText2.add("minus - " + tminus);
Toast.makeText(this, makeText2.toString(), Toast.LENGTH_SHORT).show();
// }
}
}
Just place your json data in jsonString vairable and that's all.
try {
JSONObject mainObject=new JSONObject(jsonString);
System.out.println(mainObject.toString());
System.out.println("// First Level object(s)");
System.out.println("C--> "+mainObject.getString("C"));// First Level object C
JSONArray firstArray=mainObject.getJSONArray("A");
for(int i=0;i<firstArray.length();i++){ //First Level Array A
JSONObject arrayObject =firstArray.getJSONObject(i);
System.out.println("// Second Level object(s)");
System.out.println("B--> "+arrayObject.getString("B")); // Second Level Object B
System.out.println("C--> "+arrayObject.getString("C")); // Second Level Object C
System.out.println("//Second Level Array D");
JSONArray secondLevelArray=arrayObject.getJSONArray("D");
for(int j=0;j<secondLevelArray.length();j++){
JSONObject innerArrayObject=secondLevelArray.getJSONObject(j);
System.out.println("// Third Level object(s) ");
System.out.println("ID --> "+innerArrayObject.getString("ID"));
JSONArray thirlLevelArray1=innerArrayObject.getJSONArray("One");
for(int k=0;k<thirlLevelArray1.length();k++){
JSONObject innerMostObjects=thirlLevelArray1.getJSONObject(k);
System.out.println("Plus -->"+innerMostObjects.get("Plus"));
System.out.println("Minus -->"+innerMostObjects.get("Minus"));
}
JSONArray thirlLevelArray2=innerArrayObject.getJSONArray("Two");
for(int k=0;k<thirlLevelArray2.length();k++){
JSONObject innerMostObjects=thirlLevelArray2.getJSONObject(k);
System.out.println("Plus -->"+innerMostObjects.get("Plus"));
System.out.println("Minus -->"+innerMostObjects.get("Minus"));
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
I parsed your data using Gson. The advantages of Gson are discussed previously. In addition, you can check goals of Gson.
Here is how to parse your data using Gson:
Note that I have not used code formatting standards (for example, the name of a class should use CamelCase) because you couldn't share real data.
Extracting JSON string:
While extracting JSON string use indexOf(int) instead of hard-coded 6.
jsonString = jsonString.substring(jsonString.indexOf("{"));
Parsing:
Gson gson = new Gson();
data d = gson.fromJson(reader, data.class);
for (a a1 : d.A) {
for (plusminus pm : a1.D[0].One) {
System.out.println("Plus => " + pm.Plus + " Minus => " + pm.Minus);
}
}
Required Classes:
public class data {
public String C;
public a A[];
}
public class a {
public String B;
public String C;
public d D[];
}
public class d {
public int ID;
public plusminus One[], Two[];
}
public class plusminus {
public double Plus;
public double Minus;
}
I getting this error: JSONObject cannot be converted to JSONArray
caused by this part of code:
private int parse() {
try {
Log.d("Jou", "result");
JSONArray ja = new JSONArray(data);
JSONObject jo = null;
titles.clear();
skills.clear();
for (int i = 0; i < ja.length(); i++) {
jo = ja.getJSONObject(i);
String id = jo.getString("ID");
String title = jo.getString("post_title");
//String content = jo.getString("post_content");
String date = jo.getString("post_date");
Skill skill = new Skill();
skill.setId(id);
skill.setTitle(title);
//skill.setContent(content);
skill.setDate(date);
skills.add(skill);
titles.add(title);
}
return 1;
} catch (JSONException e) {
Log.d("Jou", e.getMessage());
return 0;
}
Although I tried it before and it was exactly the same, then I added another string which is the date then I got the error. What could be wrong with the code?
This is the result from the server that needs to be parsed:
s = {"result":[{"post_id":"390","post_title":"Cart","post_date":"2017-02-07 12:17:29"},{"post_id":"421","post_title":"Front End Developer - Digital Arts","post_date":"2017-02-07 12:18:04"},{"post_id":"431","post_title":"Art Director","post_date":"2017-02-07 12:18:19"}]}
Here is the PHP script:
<?php
$dbhost = 'localhost';
$dbuser = '';
$dbpass = '';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass) or die ("Unable to connect") ;
if(! $conn )
{
echo 'Could not connect: ' . mysqli_error();
}
error_reporting(-1);
ini_set('display_errors', 'On');
mysqli_set_charset($conn, 'utf8');
$search ="";
if(isset($_REQUEST['query'] )){
$search = $_REQUEST['query'];
}
if($search != ""){
$sql = "SELECT ID,post_title,post_date FROM `wp_posts` WHERE post_title LIKE '%".$search."%'";
mysqli_select_db($conn,'');
$query = mysqli_query($conn, $sql ) or die ("Error: ".mysqli_error($conn));;
$result = array();
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
array_push($result,
array('post_id'=>$row['ID'],
'post_title'=>$row['post_title'],
'post_date'=>$row['post_date']
));}
echo json_encode(array("result"=>$result));
}else{
echo 'No search field has been sent';
}
?>
Try following code :
try {
Log.d("Jou", "result");
JSONObject object = new JSONObject(data)
JSONArray ja = object.getJSONArray("result");
JSONObject jo = null;
titles.clear();
skills.clear();
for (int i = 0; i < ja.length(); i++) {
jo = ja.getJSONObject(i);
String id = jo.getString("post_id");
String title = jo.getString("post_title");
//String content = jo.getString("post_content");
String date = jo.getString("post_date");
Skill skill = new Skill();
skill.setId(id);
skill.setTitle(title);
//skill.setContent(content);
skill.setDate(date);
skills.add(skill);
titles.add(title);
}
return 1;
} catch (JSONException e) {
Log.d("Jou", e.getMessage());
return 0;
}
Check with the following code. I hope it will work
private int parse(String data) {
try {
JSONObject jsonObject = new JSONObject(data); //get a response as Json Object and then get it as array by corresponding key
JSONArray ja = jsonObject.getJSONArray("result");
JSONObject jo = null;
for (int i = 0; i < ja.length(); i++) {
jo = ja.getJSONObject(i);
String id = jo.getString("ID");
String title = jo.getString("post_title");
//String content = jo.getString("post_content");
String date = jo.getString("post_date");
Skill skill = new Skill();
skill.setId(id);
skill.setTitle(title);
//skill.setContent(content);
skill.setDate(date);
skills.add(skill);
titles.add(title);
}
return 1;
} catch (JSONException e) {
Log.d("TAG", e.getMessage());
return 0;
}
}
There is some problem in your json response it is taking extra character in post_date try to validate it in the below link.
http://www.jsoneditoronline.org/
Please help me to parse the following JSON data given below:
{
posts: [
{
count: 1,
user_id: "1",
name: "Dave Greeneberg",
email: "daveneberg#example.com",
profile_photo: "http://phontest.lbch.com//users/user1.jpg",
contest_count: "3",
photo_count: 19,
win_count: "0",
photos: [
"images/contest/diwali1.jpg",
"images/contest/diwalc2.jpg",
"images/contest/145043cd811.png",
"images/contest/145043def03411.jpg",
"images/contest/14504ger11.jpg"
]
}
]
}
I tried the following code but values in arrayList_ph is null. I am confused about how to parse this JSON content.
JSONObject object = new JSONObject(json);
JSONArray arr = object.getJSONArray("posts");
for (int index = 0; index < arr.length(); index++) {
JSONObject object1 = arr.getJSONObject(index);
user = arr.getJSONObject(0).getString("name");
user_email = arr.getJSONObject(0).getString("email");
user_profile = arr.getJSONObject(0).getString("profile_photo");
user_count = arr.getJSONObject(0).getString("count");
user_photo_count = arr.getJSONObject(0).getInt("photo_count");
contest_count = arr.getJSONObject(0).getString("contest_count");
win_count = arr.getJSONObject(0).getString("win_count");
JSONArray ph_arr= arr.getJSONObject(0).getJSONArray("photos");
for (int in = 0; in < ph_arr.length(); in++) {
arrayList_ph.add(ph_arr.getString(in));
}
}
Please help me to parse that field.
Please try this solution.
This solutions is worked for me.
JSONObject object = new JSONObject("");
JSONArray arr = object.optJSONArray("posts");
for (int index = 0; index < arr.length(); index++) {
JSONObject object1 = arr.optJSONObject(index);
user = object1.optString("name");
user_email = object1.optString("email");
user_profile = object1.optString("profile_photo");
user_count = object1.optString("count");
user_photo_count = object1.optInt("photo_count");
contest_count = object1.optString("contest_count");
win_count = object1.optString("win_count");
JSONArray ph_arr = object1.optJSONArray("photos");
for (int in = 0; in < ph_arr.length(); in++) {
String str = ph_arr.opt(in).toString();
arrayList_ph.add(str);
}
}
change your parsing code to this ,
JSONObject object = new JSONObject(json);
JSONArray arr = object.getJSONArray("posts");
for (int index = 0; index < arr.length(); index++) {
JSONObject object1 = arr.getJSONObject(index);
user = object1.getString("name");
user_email = object1.getString("email");
user_profile = object1.getString("profile_photo");
user_count = object1.getString("count");
user_photo_count = object1.getInt("photo_count");
contest_count = object1.getString("contest_count");
win_count = object1.getString("win_count");
JSONArray ph_arr= object1.getJSONArray("photos");
for (int in = 0; in < ph_arr.length(); in++) {
String str = ph_arr.get(in).toString();
arrayList_ph.add(str);
}
}
Try -
JSONObject object = new JSONObject(json);
JSONArray arr = object.getJSONArray("posts”);
for (int index = 0; index < arr.length(); index++) {
JSONObject object1 = arr.getJSONObject(index);
user = object1.getString("name");
user_email = object1.getString("email");
user_profile = object1.getString("profile_photo");
user_count = object1.getInt("count");
user_photo_count = object1.getInt("photo_count");
contest_count = object1.getString("contest_count");
win_count = object1.getString("win_count");
JSONArray photos_arr= object1.getJSONArray("photos");
for (int in = 0; in < ph_arr.length(); in++) {
String str = ph_arr.get(in).toString();
arrayList_ph.add(str);
}
}
Please cross check Following:
1) I think your json response is not properly formatted.
Validate from this: https://jsonformatter.curiousconcept.com/
Your json response should be :
{
"posts":[
{
"count":1,
"user_id":"1",
"name":"Dave Greeneberg",
"email":"daveneberg#example.com",
"profile_photo":"http://phontest.lbch.com//users/user1.jpg",
"contest_count":"3",
"photo_count":19,
"win_count":"0",
"photos":[
{
"image":"images/contest/diwali1.jpg"
},
{
"image":"images/contest/diwalc2.jpg"
},
{
"image":"images/contest/145043cd811.png"
},
{
"image":"images/contest/145043def03411.jpg"
},
{
"image":"images/contest/14504ger11.jpg"
}
]
}
]
}
2) If that still does not work...Try debugging and post your log please...
I'm having trouble getting the String "lf" in this case North Atlantic Treaty Organization
[
{
"sf": "NATO",
"lfs": [
{
"lf": "North Atlantic Treaty Organization",
"freq": 13,
"since": 2001,
"vars": [
{
"lf": "North Atlantic Treaty Organization",
"freq": 13,
"since": 2001
}
]
}
]
}
]
//MY CODE
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray(ITEM_TAG);
for(int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
String name = c.getString("lf");
acronyms = new ArrayList<>();
acronyms.add(name);
}
} catch (Exception e) {
}
try {
JSONArray jsonArray1 = new JSONArray(JsonString);
for (int i = 0; i <= jsonArray1.length(); i++) {
JSONObject jsonObject2 = jsonArray1.getJSONObject(i);
String mStrSf = jsonObject2.getString("sf");
Toast.makeText(getApplicationContext(),mStrSf.toString(), Toast.LENGTH_LONG).show();
JSONArray jsonArray3 = jsonObject2.getJSONArray("lfs");
for (int j = 0; j <= jsonArray3.length(); j++) {
JSONObject jsonObject4 = jsonArray3.getJSONObject(j);
String mStrIf = jsonObject4.getString("lf");
String mStrFreq = jsonObject4.getString("freq");
String mStrSince = jsonObject4.getString("since");
Toast.makeText(getApplicationContext(),mStrIf+"\n"+mStrFreq+"\n"+mStrSince, Toast.LENGTH_LONG).show();
JSONArray jsonArray5 = jsonObject4.getJSONArray("vars");
for (int k = 0; k <= jsonArray5.length(); k++) {
JSONObject jsonObject6 = jsonArray5.getJSONObject(k);
String mStrIf1 = jsonObject6.getString("lf");
String mStrFreq1 = jsonObject6.getString("freq");
String mStrSince1 = jsonObject6.getString("since");
Toast.makeText(getApplicationContext(),mStrIf1+"\n"+mStrFreq1+"\n"+mStrSince1, Toast.LENGTH_LONG).show();
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
You are interpreting the json in a wrong way... if you analyse the json chain you will get this:
as you can see you have an array inside and array...
hope the picture helps you to see it better.
You have to again loop through the jsonArray to get "lf" key value.
Try this...
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray(ITEM_TAG);
for(int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
JSONArray array = c.getJSONArray("lfs");
for(int j=0;j<array.length();j++){
JSONObject obj = array.getJSONObject(j);
String name = obj.getString("lf");
}
}
} catch (Exception e) {
}
how I can access data from a JSONArray? It is this and contains this information:
"deadlines": [
{
"start": 1439539200,
"end": 1439542800
},
{
"start": 1440144000,
"end": 1440147600
},
{
"start": 0,
"end": 0
}
]
I need to have in a String tag each item "start". Thanks
EDIT
My code is this:
JSONArray array = moduleObject.specialForcedConf;
// array = [{"deadlines":[{"start":1439539200,"end":1439542800},{"start":1440144000,"end":1440147600},{"start":0,"end":0}]}]
for (int j=0; j < array.length(); j++)
{
try
{
JSONObject obj = array.getJSONObject(j);
String start = obj.getString("start");
String end = obj.getString("end");
Log.e("", "start = " + start);
}
catch (JSONException e)
{
Log.e("", "error = " + e.getMessage());
}
}
I get this error:
"error = No value for start"
Do this
JSONArray array = moduleObject.specialForcedConf;
// array = [{"deadlines":[{"start":1439539200,"end":1439542800},{"start":1440144000,"end":1440147600},{"start":0,"end":0}]}]
JSONArray jArray = array.getJSONObject(0).getJSONArray("deadlines");
for (int i = 0; i < jArray.length(); i++) // assuming your array is jArray
{
try
{
JSONObject obj = jArray.getJSONObject(i);
String start= obj.getString("start"); // store in an ArrayList
String end = obj.getString("end"); //// store in an ArrayList
}
catch (JSONException e)
{
// Error
}
}
JSONArray mJsonArray=new JSONArray("Deadlines");
for(int i=0;i<mJsonArray.length();i++){
JSONObject mJsonObject=new JSONObject(mJsonArray.get(i).toString));
String start = mJsonObject.optString("start","");
String end = mJsonObject.optString("end","");
}
Try this:
StringBuilder sb = new StringBuilder();
JSONArray arr = new JSONArray("deadlines");
for(int i=0;i<arr.length;i++){
JSONObject obj = arr.getJSONObject(i);
sb.append(obj.get("start").toString());
sb.append(",");
}
String strStartTag = sb;
JSONArray ja = new JSONArray(yourjsondata));
for (int i = 0; i < ja.length(); i++) {
JSONObject jo_feed = new JSONObject(ja.get(i).toString());
String start = jo_feed.getString("start");
}