kubiej21 kubiej21 - 3 years ago 230
JSON Question

Create json in UWP without JSON.Net

I am trying to create a json formatted string using c# in UWP without JSON.Net, but I am just not understanding how to get there. Let's say I wanted to create the following json dynamically:

[{"id":130},{"id":131},{"id":132},{"id":133},{"id":134}]


From everything I have read, it would seem that I need a class that defines the content of my json. For example:

class accountTypes
{
public int id { get; set; }
public string type { get; set; }
}


From there, it would seem that I only need to create a list of type "accountTypes" and then add each "id" to the list.

List<accountTypes> jsonList = new List<accountTypes>();
int numOfChildren = AccountTypesList.Children.Count;
for (int i = 0; i < numOfChildren; i++)
{
if (((CheckBox)AccountTypesList.Children[i]).IsChecked == true)
{
jsonList.Add(new accountTypes() { id = (int)(double)((CheckBox)AccountTypesList.Children[i]).Tag });
}
}


While I am 99% sure that the above code is very flawed, it does not crash on me, so that is a start at least. What I am struggling with now though is how I would serialize the list "jsonList". Everything I have read thus far either points to JSON.net or the JavaScriptSerializer Class, and not Windows.Data.Json. If I could see a simple example on how to serialize json using Windows.Data.Json, then I could at least visualize what is going on with my list and could correct it accordingly. That being said, how do I serialize an array or a list using Windows.Data.Json?

Answer Source

First of all, there's no built-in JSON-serializer that handles all the mapping for you. This is exactly what JSON.NET is doing for you. Therefore, you have to take the manual and long way.

To create exactly this result:

[{"id":130},{"id":131},{"id":132},{"id":133},{"id":134}]

You have to use the JsonArray class. For example, pass your jsonList object to a method like this:

public string ToJson(List<accountTypes> objectList)
{
    var jArray = new JsonArray();
    foreach (var at in objectList)
    {
        jArray.Add(ToJson(at));
    }
    return jArray.ToString();
}

Whereas you use this method to create a JsonObject for your class object itself (as manual step as well):

public JsonObject ToJson(accountTypes at)
{
    var jObj = new JsonObject();
    jObj.SetNamedValue("id", JsonValue.CreateNumberValue(at.id));
    return jObj;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download