Search code examples
androidgsonwcf-rest

How to generate mentioned json format for WCF REST API


can somebody help me with some code about how can I build my Json string as mentioned below using GSON google library in android app.

I have generated the below mentioned string using JsonStringer as mentioned below.

  JSONStringer stringer = new JSONStringer()
                    .object()
                    .key("loginRequest")
                    .object()
                    .key("UserId").value("007")
                    .key("Password").value("125987563")
                    .key("LicenseKey").value("My Project Key")
                    .key("MobileId").value("This is mobile id")
                    .endObject()
                    .endObject();

{"loginRequest":{"UserId":"007","Password":"125987563","LicenseKey":"This is License Key","MobileId":"This is mobile id"}}

Please advice that how can I generated the above mentioned string using Gson.

Thanks


Solution

  • It's nearly exactly the same:

    final StringWriter sw = new StringWriter();
    new JsonWriter(sw)
    .beginObject()
    .name("loginRequest")
    .beginObject()
    .name("userId").value("007")
    .name("password").value("123")
    .endObject()
    .endObject()
    .close();