DmainEvent DmainEvent - 2 months ago 35
C# Question

Deserialize JSON string into .net Object Nested (Collection) Dictionary

I might be being an idiot here, but I have been looking at this for the last hour now and I can't make heads or tails of how to do this. I find the best way to power through these sorts of things is to let it stew for a while, and in the meantime post a stack overflow question in case someone else had the same question.
Any way, I have a json object that looks like this:

[{
"wackyId": "wck1",
"wackyType": "wck2",
"wackyCnfdc": "wck3",
"wckyArr": [{
"fieldName": "Full_Name",
"fieldValue": "Some Text here",
"fieldConfidence": "0.3"
}, {
"fieldName": "Full_Name",
"fieldValue": "Some Text here2",
"fieldConfidence": "0.2"
}, {
"fieldName": "Full_Name",
"fieldValue": "Some Text here3",
"fieldConfidence": "0.3"
}]
}]


I am trying to convert it into use-able .net objects...

Here is what I have so far

public class WckyObj
{
[JsonProperty("wackyId")]
public string wackyId{get; set;}
[JsonProperty("wackyType")]
public string wackyType{get; set;}
[JsonProperty("wackyCnfdc")]
public string wackyCnfdc{get; set;}
[JsonProperty("fields)]
public List<multiFields> mutliFields {get; set;}
}

public class multiFields{
[JsonProperty("fields")]
public IEnumerable<IDictionary<string, string>> multiFields {get;set;}
}


right now I am currently getting back a result set with no values??? Not sure what I am missing. I have probably been staring at it to long.

EDIT: Good eye posters. I should have ran my json through JSON lint first, but I was overconfident in my skillz. Updated to be more correct

Answer

If your fieldnames matches the JSON names you don't need the attributes. This model should match your JSON:

public class WckyObj
{
    public string wackyId {get; set;}
    public string wackyType {get; set;}
    public string wackyCnfdc {get; set;}
    public List<WckyArray> wckyArr {get; set;}
}

public class WckyArray
{
    public string fieldName {get; set;}
    public string fieldValue {get; set;}
    public string fieldConfidence {get; set;}
}

Now you should be able to deserialize your JSON via JsonConvert.DeserializeObject<List<WckyObj>>