It seems everyones using Gson to get JSON from a javascript file or just to exchange JSON in Java classes. I'm trying to send a Gson object to a javascript file but I'm not sure how to get the attributes from the Gson object inside my javascript file. I haven't found any tutorial explain something like that. I'd love to see a tutorial somewhere or have someone explain me how I should do this. I haven't used Gson before.
It seems everyones using Gson to get JSON from a javascript file or just to exchange JSON in Java classes. I'm trying to send a Gson object to a javascript file but I'm not sure how to get the attributes from the Gson object inside my javascript file. I haven't found any tutorial explain something like that. I'd love to see a tutorial somewhere or have someone explain me how I should do this. I haven't used Gson before.
Share Improve this question asked Jul 28, 2014 at 9:12 Cupple KayCupple Kay 1552 silver badges14 bronze badges 3- 1 Simply use JSON.parse, assuming you don't use a library that does it for you. – Denys Séguret Commented Jul 28, 2014 at 9:13
- @dystroy I'm having a small issue but once I solve that I'll try JSON.parse and I guess you are totally right. thank you – Cupple Kay Commented Jul 28, 2014 at 9:22
- @dystroy answer my question so I can give you the reputation you earned. – Cupple Kay Commented Jul 28, 2014 at 9:36
2 Answers
Reset to default 3JSON, whose name means JavaScript Object Notation, was designed to be easy to parse in JavaScript.
Historically you could use eval
for that but now there's a dedicated function in all browsers : JSON.parse
: pass it your JSON string and it will return an object or an array.
Note that many libraries helping you query the server from a script running in a browser will also do the parsing for you so that you don't even have to call JSON.parse
.
dystroy is right.
Assuming you have read your GSON/JSON object into a javascript string, JSON.parse will create an object for you.
E.G.:
var myString = '{"firstName":"John","lastName":"Doe","nickName":"Johnny","title":"Mr","emailAddresses":["[email protected]","[email protected]"]}'
var myObject = JSON.parse(myString);
// now we have an object with properties
console.log(myObject.firstName); // logs "John"
console.log(myObject.emailAddresses[1]); // logs "[email protected]"