Get a JSON string from a SimpleJSON node.

This is my C# code:

 public static void Send(string code, JSONNode data) {
    JSONNode packet = new JSONNode();
    packet["code"] = code;
    packet["data"] = data;

    MemoryStream stream = new MemoryStream(); 
    BinaryWriter bin = new BinaryWriter(stream);

    string json = Encoding.UTF8.GetString(stream.GetBuffer());
    Debug.Log("JSON: " + json);

But the json in the debug log is blank…


How do I go about getting a JSON string out of SimpleJSON?

A bit old, but I’ll reply because I just faced the same issue.

Using JSONNode to read is all nice and well, but when you create a new json document, you shouldn’t use JSONNode, as its the base class of all the JSON data types (List, Hash/Dict, and plain data like int strings…)

JSONNode simply does not implement ToString() (Actually it does implement it, but it just returns “JSONNode” at all times, not really usable)

Here is how to create a json document with SimpleJson

JSONClass rootNode = new JSONClass();
JSONArray listNode = new JSONArray();

rootNode.Add("this_is_a_list", listNode);
rootNode.Add("this_is_a_string",  new JSONData("a string"));

listNode.Add(    new JSONData("A string!")   );
listNode.Add(    new JSONData(25235)   );
listNode.Add(    new JSONData(0.2f)   );

Debug.Log (postData.ToString());

To conclude

  • Use JSONClass for {} elements

  • Use JSONArray for elements

  • Use JSONData(value) for nodes containing data.

I was upset for this problem with SimpleJson , and ended doing my own library with pretty print:

P.S: It’s faster than SimpleJson parsing strings. :stuck_out_tongue:

It might depend on the JSON version that you are using, but if you are dealing with the one described in the wiki then you can probably just use the ToJSON method.

  public static void Send(string code, JSONNode data) {
     JSONNode packet = new JSONNode();;

     packet["code"] = code;
     packet["data"] = data;

     string json = packet.ToJSON();

     Debug.Log("JSON: " + json);

     // Actual send() or whatever.

What do you think about this? Converts any object into a JSON String. · GitHub

To use just do:


You can use it with objects, GameObjects, ScriptableObjects, MonoBehaviour, etc.