4

I want to create json data of format like this:

{
   "Credential":{
      "ref1":"Test",
      "ref2":"test",
      "ref3":"test"
   },
   "ref4":"data"
}

I tried a lot, but i did not find a way to do this. Can anyone please help me. EDIT:

I am able to put the data like below:

   {
      "ref1":"Test",
      "ref2":"test",
      "ref3":"test"
   }

Thanks in advance.

wolverine
  • 1,665
  • 5
  • 24
  • 43
  • See http://www.vogella.com/articles/AndroidJSON/article.html and http://www.roseindia.net/tutorials/json/jsonobject-java-example.shtml . These are very easy and good examples. – Never Quit Apr 28 '12 at 06:26

2 Answers2

6

You can always use JSONStringer class to do so,

JSONStringer jsonstr  = new JSONStringer()
                           .object().key("Credential")
                                    .object().key("ref1").value("Test")
                                             .key("ref2").value("test")
                                             .key("ref3").value("test")
                                    .endObject()
                                    .key("ref4").value("data")
                           .endObject();
Log.i("JSONStringer", jsonstr.toString());
MKJParekh
  • 34,073
  • 11
  • 87
  • 98
  • I get an incompatible types error in Idea12 on this. It's expecting a stringer object yet finding a writer.... odd. – Jim Wharton Sep 03 '13 at 03:14
  • can you please show me the code you are writing with the example JSON string which you are trying to build using pastebin.org @JimWharton Thanks. – MKJParekh Sep 03 '13 at 05:21
  • Even if I copy/paste the above example it gives me an error. I can use the super class as the type and it works fine. JSONWriter jsonstr = new JSONStringer(); More of an odd curiosity than an actual problem: http://i.imgur.com/tpTQitU.png – Jim Wharton Sep 03 '13 at 13:52
0

why do not you use google gson?

// get Json string
Gson gson = new Gson();
String strJson = gson.toJson(yourObject);

Is not it a better solution?

Conscious
  • 1,603
  • 3
  • 18
  • 16