Newbie Question

6 views
Skip to first unread message

fancyplants

unread,
Nov 26, 2008, 9:05:28 AM11/26/08
to google-gson
Hi,

I am looking to use Gson in my code, as it seems to be a very powerful
library, but I can't find how it does the simple stuff, namely, given
a String input, return a JsonElement output, ie a simple parser.

something like:

Gson gson = new Gson()

String someJson = "{'id':1,'name':'parent','children':[{'id':
2,'name':'child1'},{'id':3,'name':'child2'}]}";

JsonElement parsed = gson.fromJson( someJson );

Am I missing something obvious about the Gson class? It seems easy
enough to go the other way (jsonElement.toString() )

Regards,
FP

inde...@gmail.com

unread,
Nov 26, 2008, 9:12:08 AM11/26/08
to google-gson
As a user, you typically dont use JsonElement and its subclasses. You
should instead just do this:

Object foo = gson.fromJson(someJson, Foo.class);

See user guide for details: http://sites.google.com/site/gson/gson-user-guide

Inder

fancyplants

unread,
Nov 26, 2008, 9:27:39 AM11/26/08
to google-gson
Hi Inder,

I have checked out the user guide, but it all presumes that I have a
set of classes that I want to directly translate into JSON. If I did,
that would be fine,
but the JSON data is coming from a combination of several different
objects. I want to be able to take out certain attributes from those
objects and make up a JSON tree from that. Making up a another class
(ie Foo) that contains fields for each of these things is not really
what I want to do.

Not a problem at the moment - this is for an AJAX request so I can
create the JsonElement tree manually and then just spit out the
toString, although being able to specify single or double quotes
somehow would be nice.

Regards,

FP

Jacob Tomaw

unread,
Nov 26, 2008, 10:14:39 AM11/26/08
to googl...@googlegroups.com
FP,

Take a look at this discussion http://groups.google.com/group/google-gson/browse_thread/thread/412b1dab8a67961e/b6fb1b672a348c34#b6fb1b672a348c34

It includes an adapter that might help you out.

It is not the cleanest way of converting a string to a JsonElement, but it works.

Jacob
--
Jacob Tomaw
tfl:The Flatiron Life (http://tomaw.com)
Follow me on Twitter! (http://twitter.com/JacobTomaw)

fancyplants

unread,
Nov 26, 2008, 10:25:38 AM11/26/08
to google-gson
Ah this is just the ticket, thanks!

FP

On Nov 26, 3:14 pm, "Jacob Tomaw" <jacob.to...@gmail.com> wrote:
> FP,
>
> Take a look at this discussionhttp://groups.google.com/group/google-gson/browse_thread/thread/412b1...
>
> It includes an adapter that might help you out.
>
> It is not the cleanest way of converting a string to a JsonElement, but it
> works.
>
> Jacob
>
Reply all
Reply to author
Forward
0 new messages