Answer the question
In order to leave comments, you need to log in
How to generate Json in C#, if the structure is dynamic, without prescribing all possible options?
I am generating json using Newtonsoft.Json library;
The answer should be like
{Command:"CommandName", Data:{"Param1":1,"Param2:2"}}
{Command:"FilesList", Data:{"Files":["file1","file2","file3","file4"]}}
{Command:"UserInfo", Data:{"UserId":1, "UserName": "Roman" ....}}
string data = JsonConvert.SerializeObject(DataInfo, Formatting.Indented);
Answer the question
In order to leave comments, you need to log in
You can create classes like this:
public class CommandResult
{
public string Command {get;set;}
}
public class CommandResult<T>:CommandResult
{
public T Data {get;set;}
}
public class FilesList
{
public string[] Files {get;set;}
}
public class UserInfo
{
...
}
public class MyAwesomeController:ApiController
{
public CommandResult<FilesList> GetFilesList(){
...
return new CommandResult<FilesList> (){
Command = "FilesList",
Data = new FilesList(){Files = new []{"file1","file2","file3","file4"}}
};
}
public CommandResult<UserInfo> GetUserInfo(){
...
}
}
public class MyAwesomeCommands
{
private CommandResult<FilesList> _getFilesList(){
...
return new CommandResult<FilesList> (){
Command = "FilesList",
Data = new FilesList(){Files = new []{"file1","file2","file3","file4"}}
};
}
public string GetFilesList(){
var data = getFilesList();
return JsonConvert.SerializeObject(data);
}
public string GetUserInfo(){
...
}
}
And dynamic does not suit?
dynamic filesListCommand = new
{
Command = "FilesList",
Data = new { Files = new[] { "file1", "file2", "file3", "file4" } }
};
dynamic userInfoCommand = new
{
Command = "UserInfo",
Data = new { UserId = 1, UserName = "Roman" }
};
string filesListCommandJson = JsonConvert.SerializeObject(filesListCommand);
string userInfoCommandJson = JsonConvert.SerializeObject(userInfoCommand);
dynamic filesListCommandParsed = JObject.Parse(filesListCommandJson);
dynamic userInfoCommandJsonParsed = JObject.Parse(userInfoCommandJson);
string file1Value = filesListCommandParsed.Data.Files[0]; // file1
string romanValue = userInfoCommandJsonParsed.Data.UserName; // Roman
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question