Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
From JSONArray to Java Array4:35 with Ken Alger
Let's look at how to convert our data from JSONArray to be used in a Java Array.
Welcome back, how did you do? 0:00 Hopefully this is just review for you. 0:02 We start off here creating a new array of hour objects. 0:05 So Hour array. 0:12 We'll call it hours, so new_Hour array, 0:15 Data.length. 0:22 We can then loop through all the items in the JSON array, 0:28 get the data we want from each one, and set a new Hour object in the hours array. 0:31 I'll do it in a for loop. 0:37 Scroll up here a little bit, give ourselves some room. 0:40 So for. 0:45 So as long as i is less than the length of our data. 0:51 Our incrementor. 0:57 One thing to note here is that length is a method, not a property. 1:00 With a normal array, like our array of hours, 1:06 we get the length via a property called length, not a method. 1:10 It's easy to confuse the two, but that's why we have auto-complete. 1:15 Back to our loop. 1:20 Our first step is to create a new JSON object for the item at position i. 1:21 So JSONObject, we'll call it 1:26 jsonHour, we want data, 1:31 getJSONObject at position i. 1:35 Now we create an hour object, 1:42 And set our values from the JSON. 1:50 So setSummary(jsonHour). 1:54 GetString, and it was called summary. 2:01 We'll set our icon. 2:08 Again, that was a string. 2:14 We'll set our temperature, which is a double. 2:21 Called temperature. 2:32 We'll set our time, Which was a long, 2:35 Called "time". 2:47 And we'll set our timezone. 2:50 We'll pass in timezone. 2:55 And now we can return hours. 3:05 All right, let's verify this is working by using the debugger. 3:11 We can set a break point here where we're defining hour. 3:15 Set a break point, and we run our app with the debugger. 3:19 There's our hour. 3:44 And we see it starts populating. 3:49 Very nice. 3:52 And our data is coming through. 3:52 Terrific, let's not forget to remove this break point before we move on. 3:54 Fantastic work. 4:05 We've updated our data model can handle this more complex set of data, and 4:07 then we saw how to use the JSON array class to work with arrays of JSON objects. 4:11 With this skill set, you are pretty much a master of working with JSON in Android. 4:16 It can get a little tedious though. 4:21 In true Android and open source fashion, there are some excellent 4:23 third party libraries available that make working with json data even easier. 4:27 If you're interested, check out the links in the teacher's notes. 4:32
You need to sign up for Treehouse in order to download course files.Sign up