使用Json.net将项添加到JSON

时间:2016-04-14 02:09:37

标签: json json.net

使用json.net,我创建了一个json字符串,它是我的数据表的序列化版本,并且能够将其反序列化回数据表。我们说我的序列化文本如下所示:

[{ username: "alan", firstName: "Alan", lastName: "Johnson", email: "alan@test.com" },
{ username: "allison", firstName: "Allison", lastName: "House", email: "al@test.com" },
{ username: "ryan", firstName: "Ryan", lastName: "Carson", email: "ryan@test.com" } ]

我想要做的是在[之后]或者在结尾之后添加一些文本,这些文本将包含在json文本中,而不会阻止反序列化返回到数据表。

我使用serialize命令,有时使用类对象作为序列化命令的第二个(可选)参数,有时不使用。如果我使用第二个参数,它会产生更详细的json,其中包括表和列定义信息。

无论哪种方式,我想在json文本中添加一个段,它将指示查找的成功或失败,但不会导致反序列化中断。

任何人都可以建议使用json.net方法吗?

...谢谢

1 个答案:

答案 0 :(得分:0)

public class Users
{
    public string username { get; set; }
    public string firstName { get; set; }
    public string lastName { get; set; }
    public string email { get; set; }
}

dynamic usercollectionWrapper = new
{           
    userList = new List<Users>
    {    
        new Users()
        {
            username= "alan", firstName= "Alan", lastName= "Johnson", email= "alan@test.com"
        },
        new Users()
        {
            username= "allison", firstName= "Allison", lastName= "House", email= "al@test.com"
        },
        new Users() 
        { 
            username= "ryan", firstName= "Ryan", lastName= "Carson", email= "ryan@test.com" 
        }
    }
};

var output = JsonConvert.SerializeObject(usercollectionWrapper);

小提琴:https://dotnetfiddle.net/aAZ3Ah

<强>更新

public class Users
{
    public string username { get; set; }
    public string firstName { get; set; }
    public string lastName { get; set; }
    public string email { get; set; }
}

public class RootUsers
{
    public string status { get; set; }          
    public List<Users> data { get; set; }
}

dynamic usercollectionWrapper = new
{
    add = new RootUsers()
    {
        status = "success",         
        data = new List<Users>
        {    
            new Users()
            {
                username= "alan", firstName= "Alan", lastName= "Johnson", email= "alan@test.com"
            },
            new Users()
            {
                username= "allison", firstName= "Allison", lastName= "House", email= "al@test.com"
            },
            new Users() 
            { 
                username= "ryan", firstName= "Ryan", lastName= "Carson", email= "ryan@test.com" 
            }
        }
    }
};

var output = JsonConvert.SerializeObject(usercollectionWrapper);

小提琴:https://dotnetfiddle.net/Ic6M1Z