Venelin
Venelin

Reputation: 3308

C# - Trying to convert Dictionary to JSON

Here is my code:

public class JsonData
{
    public string header;
    public Dictionary<string, string> data = new Dictionary<string, string>();
    public int connectionId;
}

JsonData SendData = new JsonData();
SendData.header = "01";
SendData.data.Add("text", "What is Lorem Ipsum?Lorem ");
SendData.data.Add("accId", "123");
SendData.connectionId = 12;

string json = JsonUtility.ToJson(SendData);

Everything is fine but somehow the key data in the converted JSON string does not appear at all.

The string json looks like this:

{"header":"01","connectionId":12}

instead of:

{"header":"01","data":{"text":"What is Lorem Ipsum?Lorem ","accId":"123"},"connectionId":12}

Where is my mistake ? Why i can not receive result like this ?

Upvotes: 2

Views: 8538

Answers (2)

Marisa
Marisa

Reputation: 792

From https://docs.unity3d.com/ScriptReference/JsonUtility.ToJson.html.

Note that while it is possible to pass primitive types to this method, the results may not be what you expect; instead of serializing them directly, the method will attempt to serialize their public instance fields, producing an empty object as a result. Similarly, passing an array to this method will not produce a JSON array containing each element, but an object containing the public fields of the array object itself (of which there are none). To serialize the actual content of an array or primitive type, it is necessary to wrap it in a class or struct.

Try exposing the contents of data in a property, like the following.

    public string dataOutput
    {
        get
        {
            return string.Join(",", data.Select(x => string.Format("\"{0}\":\"{1}\"", x.Key, x.Value)));
        }
    }

Upvotes: 1

Felipe Oriani
Felipe Oriani

Reputation: 38598

Use Newtonsoft.Json to get the right json. Given you have it referenced on your project use the namespace:

using Newtonsoft.Json;

And use the JsonConvert.SerializeObject static method:

string json = JsonConvert.SerializeObject(SendData);

Upvotes: 6

Related Questions