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

2
  • 1
    What exactly are you trying to do that does not work? Commented Mar 10, 2016 at 10:05
  • Possible duplicate of How to create JSON string in C# Commented Mar 10, 2016 at 10:14

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Added an edit that actually produces the correct JSON with values from above into the json variable.
Tks a lot, this was helpful!
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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.