how do I serialize a JS function literal?

259 views
Skip to first unread message

Dudenhaufer

unread,
May 25, 2010, 3:05:04 PM5/25/10
to google-gson
I need to include a javascript function literal in my json output, but
I cannot figure out how to do it. This is my desired json output
snippet:
{"formatter": function() {return '<b>'+ this.point.name +'</b>: '+
this.y +' %';}}

I have a static inner class that contains a single element, but
instead of having the string wrapped in quotes, I want the function
literal to be left alone.

static class tooltip
{
public String formatter = "function(){return '<b>'+ this.point.name
+'</b>: '+ this.y +' %';}";
public tooltip(){}
}

From reading the docs, it seems like I should be able to write my own
serializer for this. Here's my serialier class, but the two problems
I'm running into are 1) I cannot subclass JsonPrimitive, which seems
like my best route, and 2) if I try to subclass JsonElement, I run
into issues where the underlying gson code is expecting either a
subclass of JsonPrimitive, JsonObject, etc.

class tooltipSerializer implements JsonSerializer<tooltip>
{
@Override
public JsonElement serialize(
com.mypath.tooltip tooltip,
Type type, JsonSerializationContext context) {
//return new JsonPrimitive("foo"); // this didn't leave the string
alone
return new MyJsonElement("foo"); // fails with
java.lang.IllegalStateException: This is not a JSON Primitive.
}
}

MyJsonElement class:

package com.google.gson;
import java.io.IOException;

public class MyJsonElement extends JsonElement {

private String value;

public MyJsonElement(final String input)
{
this.value = input;
}

@Override
protected void toString(Appendable sb, Escaper escaper) throws
IOException {
sb.append(value);
}
}

Hopefully I'm missing something obvious here, any help is much
appreciated.

Joel

unread,
May 26, 2010, 1:45:09 PM5/26/10
to google-gson
This is currently not supported due to some security concerns.

fanc...@gmail.com

unread,
May 13, 2013, 9:15:11 PM5/13/13
to googl...@googlegroups.com
I have the same problem. is there any other tools can do this?
Reply all
Reply to author
Forward
0 new messages