1

I have a JSON String structured in the following way and it throws an exception passing it into JSONArray timeJSONArray = new JSONArray(time);

This is the error Value [{"daysByte":158,"from":1020,"to":1260},{"daysByte":96,"from":1020,"to":1320}] at 0 of type org.json.JSONArray cannot be converted to JSONObject This is how I receive the array and I can't change it, so I'm having trouble converting it to a JSON Object instead of a JSON String which is the format it's currently in. What am I doing wrong?

[   
   [  
      {  
         "daysByte":30,
         "from":660,
         "to":1290
      },
      {  
         "daysByte":96,
         "from":660,
         "to":1320
      },
      {  
         "daysByte":128,
         "from":1050,
         "to":1290
      }
   ],
   [  
      {  
         "daysByte":252,
         "from":690,
         "to":840
      },
      {  
         "daysByte":252,
         "from":1050,
         "to":1260
      }
   ]
]

This is the code I am working with. I'm getting the value passed in as a string

public ArrayList<String> getTimeList(String time){

        System.out.println("PLACES ACTIVITY " + time);
        ArrayList<String> times = new ArrayList<>();
        try{
            //JSONObject timeJSONObject = new JSONObject(time);
            JSONArray timeJSONArray = new JSONArray(time);
            ArrayList<LegacyTimeSpan> timeSpanList = new ArrayList<>();

            LegacyTimeSpanConverterImpl converter = new LegacyTimeSpanConverterImpl();


            for(int i = 0; i < timeJSONArray.length(); i++){

                int daysByte = timeJSONArray.getJSONObject(i).getInt("daysByte");
                int from = timeJSONArray.getJSONObject(i).getInt("from");
                int to = timeJSONArray.getJSONObject(i).getInt("to");

                System.out.println("TO " + to);

                LegacyTimeSpan timeSpan = new LegacyTimeSpan(daysByte, from, to);
                timeSpanList.add(timeSpan);

            }

            Log.d("Time span list", timeSpanList.toString());
            WeekSpan weekSpan = converter.convertToWeekSpan(timeSpanList);
            List<DayTimeSpanPair> dayTimeSpanPair = weekSpan.toDayTimeSpanPairs();
            for(int i = 0; i< dayTimeSpanPair.size(); i++){

                String timeRange = buildTimeString(dayTimeSpanPair.get(i));
                times.add(timeRange);


            }
        } catch(JSONException e){
            Log.d("PLACES EXCEPTION JSON",e.getMessage());
        }

        return times;
    }
3
  • 2
    Don't just show the JSON, show the code as well. Always show the code. Commented Feb 26, 2016 at 6:28
  • See my answer to the above problem , basically there two arrays one within other , hence your have to consider the arrays, Currently you are trying to put first array to an JSONObject which is not correct Commented Feb 26, 2016 at 6:32
  • timeJSONArray.getJSONObject(i)? You don't have a JsonObject at i, you have an array Commented Feb 26, 2016 at 6:42

6 Answers 6

1

This Code should work i think as u declare the json Format.

             [
                [
                  {
                  } ,{},{}             // Json Object Structure as u defined in you Question
topArray =      ],
                [  
                  {
                  },{},{}
                ]
             ]


for(JSONArray objArray : topArray){
    for(JSONObject eachObject : objArray){
   System.out.println(eachObject.get("daysByte"););
   System.out.println(eachObject.get("from");
   System.out.println(eachObject.get("to");
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

Hi following code is working for your json I have tried. It is specific for your json not generic. so if you want you can use it.

try{
    JSONArray jsonArray = new JSONArray(data); //insted "Data" pass your json Strint
       for(int i=0 ; i<jsonArray.length() ; i++){
           JSONArray internalArray = jsonArray.getJSONArray(i);
           for(int j = 0 ; j < internalArray.length() ; j++){
               JSONObject internalObject = internalArray.getJSONObject(j);
               Log.d("data" ,  internalObject.getString("daysByte"));
               Log.d("data" ,  internalObject.getString("from"));
               Log.d("data" ,  internalObject.getString("to"));
           }
       }

   }catch(Exception e){
       Log.d("data" ,"Error");
   }
}

5 Comments

If you find it useful then please mark it as answer
It won't get past the first line. That is where it throws the exception so no code executes after it.
I didn't get your comment will you please explain your problem again
The Exception gets thrown at the line JSONArray jsonArray = new JSONArray(data) so nothing below it will execute. It will just jump straight to the "catch"
I have tested using same json given by you it is working there might be chances you are getting different json
0

You have two arrays, one array within other.

You have to do like this:

for(JSONArray temp: timeJsonArray)
{
   // try to convert to json object
}

2 Comments

If the error is thrown at this line JSONArray timeJSONArray = new JSONArray(time); then how will I be able to make a for loop after it?
stackoverflow.com/a/2414332/5188230 see this, its a two dimensional JSON array
0

It is a 2D Array.

System.out.println("days");
String content = new Scanner(new File("C:/day.txt")).useDelimiter("\\Z").next();
Day[][] customDayWrap = new Gson().fromJson(content, Day[][].class);
    for (Day[] days : customDayWrap) {
        for (Day day : days) {
            System.out.println(day.getDaysByte());
            System.out.println(day.getFrom());
            System.out.println(day.getTo());
        }
    }

And your Day Class will be something like this.

public class Day {

@SerializedName("daysByte")
@Expose
private Integer daysByte;
@SerializedName("from")
@Expose
private Integer from;
@SerializedName("to")
@Expose
private Integer to;

/**
 * 
 * @return
 *     The daysByte
 */
public Integer getDaysByte() {
    return daysByte;
}

/**
 * 
 * @param daysByte
 *     The daysByte
 */
public void setDaysByte(Integer daysByte) {
    this.daysByte = daysByte;
}

/**
 * 
 * @return
 *     The from
 */
public Integer getFrom() {
    return from;
}

/**
 * 
 * @param from
 *     The from
 */
public void setFrom(Integer from) {
    this.from = from;
}

/**
 * 
 * @return
 *     The to
 */
public Integer getTo() {
    return to;
}

/**
 * 
 * @param to
 *     The to
 */
public void setTo(Integer to) {
    this.to = to;
}

}

I tested this (I am using Google GSON library), and I was able to successfully read it.

Comments

0

Basically, there are two JSON arrays but you are accessing only one arrays that is why that error is shown

   try {
        JSONArray jsonArray = new JSONArray(a);

        for (int j=0;j<jsonArray.length();j++) {

            JSONArray timeJSONArray = jsonArray.getJSONArray(j);

            for(int i = 0; i < timeJSONArray.length(); i++){

                int daysByte = timeJSONArray.getJSONObject(i).getInt("daysByte");
                int from = timeJSONArray.getJSONObject(i).getInt("from");
                int to = timeJSONArray.getJSONObject(i).getInt("to");

                System.out.println("TO " + to);


            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

4 Comments

It is a single array only. Please check it.
@chandankumarkushwaha its a two array see this : stackoverflow.com/a/2414332/5188230
But in overall it is added in a single array. Please check
hey man goto this link and paste your json there understand the structure first then you will be able to solve it json.parser.online.fr
0

After 1 hour of debugging your Json array I finally managed to figure out your actual issue. Its not only a Json Array its array inside the array.

So loop like this,

 for (int i = 0; i < timeJSONArray.length(); i++) {

            for(int j= 0;j<i;j++) {
                int daysByte = timeJSONArray.getJSONArray(i).getJSONObject(j).getInt("daysByte");
                int from = timeJSONArray.getJSONArray(i).getJSONObject(j).getInt("from");
                int to = timeJSONArray.getJSONArray(i).getJSONObject(j).getInt("to");
                Log.d("dataRecieved", "daybyte " + daysByte + "from " + from + "to " + to);
            }
}

And do others as you need.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.