使用相同的json格式进行序列化

时间:2016-10-21 07:51:08

标签: c# json

我有一个如下的json数据:

{
"ResourceStrings": 
   [
    {
        "StringKey": "TestKey",
        "StringID": 1,
        "Value": "This translate need to be done123fdff"
    }, 
    {
        "StringKey": "SampleKey",
        "StringID": 2,
        "Value": "This translate need to be done345fdfd"
    }

]
}

我把它转换为类,所以在创建的类下面:

public class ResourceString
{
    public string StringKey { get; set; }
    public int StringID { get; set; }
    public string Value { get; set; }
}
public class RootObject
{
    public List<ResourceString> ResourceStrings { get; set; }
}

现在我有一些xliff格式的数据,我从这个元素中获取并在Rootobject中进行更新,如下所示:

     XmlDocument docXLIFF = new XmlDocument();
    docXLIFF.LoadXml(xliffdata);
    var jsondata = JsonConvert.DeserializeObject<RootObject>      (sameJsonDataAsAbove);
    List<ResourceString> rstList = jsondata.ResourceStrings.ToList();

    XmlNodeList xmlNodes = docXLIFF.SelectNodes("/xliff/file/body/trans-unit");
    foreach (XmlNode node in xmlNodes)
    {
        var getTransID = rstList.Where(t => t.StringID.ToString() == node.Attributes["id"].Value).FirstOrDefault();
        if (getTransID != null)
        {
            var getTargetValue = node.InnerText;
            getTransID.Value = getTargetValue;
        }
    }

所以在上面的代码中我用jsonList id检查xliff元素的id,并且匹配我得到了json列表中元素和设置的值。 完成此操作后,我需要更新的json列表,其格式与我上面提到的相同。但我只得到以下内容:

    {
        "StringKey": "TestKey",
        "StringID": 1,
        "Value": "This translate need to be done123fdff"
    }, {
        "StringKey": "SampleKey",
        "StringID": 2,
        "Value": "This translate need to be done345fdfd"
    }

如何实现相同的json结构?

1 个答案:

答案 0 :(得分:1)

我认为您需要将字符串解析为数组: - )

请参阅此帖子以获取更多帮助:

Parse this json string to string array c#

编辑: 对不起利亚姆,你走吧

    //add [] to the string so it's an array!
var xcliff = " [ { " +
    "\"StringKey\": \"TestKey\"," +
    "\"StringID\": 1," +
    "\"Value\": \"This translate need to be done123fdff\"" +
"}, {" +
    "\"StringKey\": \"SampleKey\"," +
    "\"StringID\": 2," +
    "\"Value\": \"This translate need to be done345fdfd\"" +
"}]";

var jd = new JavaScriptSerializer().Deserialize<List<ResourceString>>(xcliff);
var ro = new RootObject { ResourceStrings = jd};