最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

servlets - From Gson to javascript - Stack Overflow

programmeradmin0浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 3

JSON, 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]"
发布评论

评论列表(0)

  1. 暂无评论