How to add a prefix before each key when converting into json

868 views
Skip to first unread message

Joshua Wang

unread,
Aug 19, 2013, 9:03:50 PM8/19/13
to googl...@googlegroups.com
I'm a newer in gson. I need to add a prefix before each key when converting into json:
For example:
an java class:
public class A{
  private string a;
  private string b;
}

Maybe  call a function(convert) wrote by me:

A obj = new A();
obj.a = "1";
my.own.JsonUtil jUtil = new JsonUtil();
jUtil.convert(obj,"pre");

the result like this(prefix string "pre" were added before each key):
json: {"pre.a":"1","pre.b":""}

Before gson I had used another json library and I'm doing this be added a function into JSONObject :
public String toString(String prex) {
        try {
            Iterator     keys = this.keys();
            StringBuffer sb = new StringBuffer("{");
            while (keys.hasNext()) {
                if (sb.length() > 1) {
                    sb.append(',');
                }
                Object o = keys.next();
                sb.append(quote(prex + "." + o.toString()));
                sb.append(':');
                sb.append(valueToString(this.map.get(o)));
            }
            sb.append('}');
            return sb.toString();
        } catch (Exception e) {
            return null;
        }
    }

But how should I do with gson? If you have any idea, please do me a favour. Thank you!

Martin Grajcar

unread,
Aug 22, 2013, 10:22:32 AM8/22/13
to googl...@googlegroups.com


--
You received this message because you are subscribed to the Google Groups "google-gson" group.
To unsubscribe from this group and stop receiving emails from it, send an email to google-gson...@googlegroups.com.
To post to this group, send email to googl...@googlegroups.com.
Visit this group at http://groups.google.com/group/google-gson.
For more options, visit https://groups.google.com/groups/opt_out.

Reply all
Reply to author
Forward
0 new messages