Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialOrla McGreal
1,625 PointsNeed help with the challenge- I don't get how to set the variables using the jsonData object...
I understand the variables and their appropriate values but don't understand how to set them in the object that's already been made elsewhere.
Could somebody explain?
Thanks in advance!
// A JSONObject variable named 'jsonData'
// was loaded from the data.json file.
private jsonData () {
private String name;
private String publisher;
private String language;
}
{
"name":"Treehouse Book Series",
"publisher":"Wiley",
"language":"English",
"books":[
{
"title":"HTML5 Foundations",
"author":"Matt West",
"pages":384
},
{
"title":"CSS3 Foundations",
"author":"Ian Lunn",
"pages":352
}
]
}
2 Answers
Steve Hunter
57,712 PointsHi there,
You can take each element and use getString()
to access the value for each key, like so:
String name = jsonData.getString("name");
String publisher = jsonData.getString("publisher");
String language = jsonData.getString("language");
Hope that helps!
Steve
Steve Hunter
57,712 PointsAh, right; you're inside the challenge trying to use your variable, books
rather than the provided jsonData
. I get you now!
Right, the JSONObject constructor takes a string. You have passed it a JSONObject. The conversion has already taken place. So, passing jsonData
into the constructor, new JSONObject(jsonData);
will fail as you can't cast from one type to the other.
Essentially, you don't need the constructor. If you wanted to use your object books
just assign jsonData
to it:
JSONObject books = jsonData;
But that's pretty pointless, really.
I hope that helps.
Steve.
CD Lim
4,782 PointsThanks !!! A lot !!!
Orla McGreal
1,625 PointsOrla McGreal
1,625 PointsThat does - thanks !
CD Lim
4,782 PointsCD Lim
4,782 PointsHi Steve, I was trying to create a new object and link to it just as it is shown in the tutorial, may I ask why it does not work ?
Steve Hunter
57,712 PointsSteve Hunter
57,712 PointsHIya,
The last three lines look fine, assuming your JSON format is identical to that in the challenge.
What have you stored in your variable
jsonData
? Is that in the form of a String?Steve.