user7305885
user7305885

Reputation:

C# JObject parsing

How to parse this json object???

{{
    "track": "t1",
    "category": {
        "c1": {
            "skills": [
                "s1"
             ]
        },
        "c2": {
            "skills": [
                "s1",
                "s2"
             ]
        }
    }
}}

This is what I've tried so far and yet I don't understand how to do this in c#. This is my first time doing c# projects and still not able to move from JAVA to C#

[HttpPost]
[Route("api/TCSAPI/SaveTCS")]
public HttpResponseMessage SaveTCS([FromBody] dynamic tcsObject)
{
    JToken token = JObject.Parse(tcsObject.ToString());

    string track = token.SelectToken("track").ToString();
    List<JToken> category = token.SelectToken("category").ToList();
    foreach (var cat in category) {
        var data = cat;
        // dont know after this
    }

    return Helper.ComposeResponse(HttpStatusCode.OK, string.Empty);
}

Upvotes: 1

Views: 2613

Answers (1)

Mohit S
Mohit S

Reputation: 14064

The problem with the JSON is {{ and }} so you need to trim the JSON string to make it { and }

string jsonstr = File.ReadAllText(YourJSONFile);
jsonstr = jsonstr.Replace("{{", "{");
jsonstr = jsonstr.Replace("}}", "}");

and then you can install Newtonsoft JSON to deseralize the JSON.

Your class sturcture would look something like this

public class C1
{
    public List<string> skills { get; set; }
}

public class C2
{
    public List<string> skills { get; set; }
}

public class Category
{
    public C1 c1 { get; set; }
    public C2 c2 { get; set; }
}

public class DataItem
{
    public string track { get; set; }
    public Category category { get; set; }
}

Then you can deseralize it like

var ser = JsonConvert.DeserializeObject<DataItem>(jsonstr);

Edit

Since C1 and C2 are dynamic you can use class like this

public class SomeCat
{
    public List<string> skills
    {
        get;
        set;
    }
}
public class DataItem
{
    public string track
    {
        get;
        set;
    }
    public Dictionary<string, SomeCat> Category
    {
        get;
        set;
    }
}

and deseralize it like

string jsonstr = File.ReadAllText(YourJSON);
jsonstr = jsonstr.Replace("{{", "{");
jsonstr = jsonstr.Replace("}}", "}");
var ser = JsonConvert.DeserializeObject<DataItem>(jsonstr);

The screenshot to see how the data looks and you can access it using the index.

ScreenShot

Upvotes: 1

Related Questions