使用JSON.net在Dictionary中使用数组定义类

时间:2016-04-06 15:26:52

标签: c# arrays json dictionary

我正在尝试在Dictionary<string,string>

中执行以下操作
{
    "name": "Bob Barker",
    "devName": "InformationServices",
    "ReturnedData": [{
        "level_heading": "blah1",
        "DeliverBestMedicalValue": "blah2",
        "level_question": "blah3"
    }]
}

我可以添加名称 devName ,但我不确定如何添加数组的 ReturnedData 部分列表,以便它将作为上面的布局返回?

我正在使用的示例代码:

febRecords.RootObject febRecordsData = JsonConvert.DeserializeObject<febRecords.RootObject>(serverResponse);
Dictionary<string,string> febFormData = new Dictionary<string,string>();

febFormData.Add("name", data.firstname.ToString());
febFormData.Add("devName", febData["Data"]["DevisionName"].ToString());
febFormData.Add("ReturnedData", ???); //<-this is where I am stuck

return Ok(JsonConvert.SerializeObject(febFormData, Newtonsoft.Json.Formatting.Indented));

如你所见, febFormData.Add(“ReturnedData”,???); 是我被卡住的地方,并且不知道该怎么办才能让字典输出正确的JSON格式就像我想要的那样。

任何帮助都会很棒!

更新

这会是班级需要看的吗?

public class theOutput
{
    public string name { get; set; }
    public string devName { get; set; }
    public List<string> ReturnedData { get; set; }
}

1 个答案:

答案 0 :(得分:2)

根据@Panagiotis Kanavos的建议,你最好让.NET实体匹配你的JSON数据。例如:

// propertyname attributes can be ignored if property names 
// match the json data property names 1:1

[JsonObject]
public class MyClass
{
    public MyClass()
    {
        ReturnedData = new List<ReturnedData>();
    }

    [JsonProperty(PropertyName = "name")]
    public string Name { get; set; }

    [JsonProperty(PropertyName = "devName")]
    public string DevName { get; set; }

    [JsonProperty(PropertyName = "ReturnedData")]
    public List<ReturnedData> ReturnedData { get; set; }
}

[JsonObject]
public class ReturnedData
{
    [JsonProperty(PropertyName = "level_heading")]
    public string LevelHeading { get; set; }

    [JsonProperty(PropertyName = "DeliverBestMedicalValue")]
    public string DeliverBestMedicalValue { get; set; }

    [JsonProperty(PropertyName = "level_question")]
    public string LevelQuestion { get; set; }
}

这样可以更容易地转换为JSON或从JSON转换。

[TestMethod]
public void TestSome()
{
    string json = @"{
        ""name"": ""Bob Barker"",
        ""devName"": ""InformationServices"",
        ""ReturnedData"": [{
            ""level_heading"": ""blah1"",
            ""DeliverBestMedicalValue"": ""blah2"",
            ""level_question"": ""blah3""
        }]
    }";

    var obj = JsonConvert.DeserializeObject<MyClass>(json);
    Assert.IsTrue(JToken.DeepEquals(JObject.Parse(json), JObject.FromObject(obj)));
}

您始终可以使用例如JSON数据从JSON数据生成存根。 http://json2csharp.com/

这里的“现场”.NET小提琴也是https://dotnetfiddle.net/9ACddp