1

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);
}

1 Answers1

1

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

Community
  • 1
  • 1
Mohit S
  • 13,723
  • 6
  • 34
  • 69
  • c1 and c2 is dynamic - means it is not always that it is a c1 or c2 because it is base from what i input in textbox. also when i use json.GetType(), i get a type of jobject. –  Jan 13 '17 at 02:22
  • thank you very much. another problem how to access the data in `var ser`? it said that the datatype is dynamic –  Jan 13 '17 at 03:26