在C#中创建一个JSON字符串

时间:2016-03-10 10:03:00

标签: c# json web-services

我正在尝试为我的REST Web服务创建一个要作为JSON返回的对象。

我希望得到这样的回复:

{
    "message": [
    {
        "name": "whatever.bmp"
    }
    ],
    "errors": null,
    "FileInflected": 0,
    "path": "C:\thepath"
}

那么,如何在C#中更改类(eFileOutput)?

如何更改下面的课程?

目前,我可以创建类似的输出:

{
  "message": "Hello World",
  "errors": null,
  "FileInfected": 0,
  "path": "C:\bla bla..."
}

和我的C#类如下:

[DataContract]
    public class eFileOutput
    {
        [DataMember]
        public string message { get; set; }
        [DataMember]
        public string errors { get; set; }
        [DataMember]
        public Int32 FileInfected { get; set; }
        [DataMember]
        public string path { get; set; }
    }

韩国社交协会

2 个答案:

答案 0 :(得分:1)

这是代表您所声明的JSON的类:

public class Message
{
    public string name { get; set; }
}

public class MyObject
{
    public List<Message> message { get; set; }
    public object errors { get; set; }
    public int FileInflected { get; set; }
    public string path { get; set; }
}
var json = Newtonsoft.Json.JsonConvert.SerializeObject(new MyObject
{
    message = new List<Message>
    {
        new Message {name = "whatever.bmp"}
    },
    FileInflected = 0,
    path = @"c:\thepath"
});

编辑(感谢devzero):然后你可以使用Newtonsoft(我最喜欢的)或JavaScriptSerializer序列化,如下所示:Turn C# object into a JSON string in .NET 4

答案 1 :(得分:0)

public class MyObject
{
    public Message Message { get; set; }

    public List<Error> Errors { get; set; }

    public int FileInflected { get; set; }

    public string Path { get; set; }
}

public class Message
{
    public string Name { get; set; }
}

public class Error
{
    //Whatever you want
}

如果您想将成员序列化为camelCase,请按以下方式进行描述:

var jsonSerializerSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
var json = JsonConvert.SerializeObject(c, jsonSerializerSettings);