0

I'm trying to create an object to be returned as JSON for my REST Web Service.

I wish to get something returned like this:

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

So, how can I change the class (eFileOutput) in C#?

How can I change the class I have below?

Currently I'm able to create similar output like this:

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

and my C# class is as follows:

[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; }
    }

Tks

Trowa
  • 355
  • 1
  • 6
  • 20
  • 1
    What exactly are you trying to do that does not work? – StarterPack Mar 10 '16 at 10:05
  • Possible duplicate of [How to create JSON string in C#](http://stackoverflow.com/questions/1056121/how-to-create-json-string-in-c-sharp) – VVN Mar 10 '16 at 10:14

2 Answers2

1

This is the classes that represent the JSON you've stated:

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"
});

Edit (thanks to devzero): Then you can serialize using Newtonsoft (my favorite) or JavaScriptSerializer as stated here: Turn C# object into a JSON string in .NET 4

Community
  • 1
  • 1
Felix Av
  • 1,254
  • 1
  • 14
  • 22
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
}

and if You want to serialize member as camelCase, describe like this:

var jsonSerializerSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
var json = JsonConvert.SerializeObject(c, jsonSerializerSettings);
deyu
  • 329
  • 2
  • 6