0

I am new to C# and I am trying to create an object in a similar way that we create them in js:

var obj = {
'method' : 'connect',
'data' : {
    'somekey'  : 'data',
    'somekey2' : 'data',
    'somekey3' : 'data',
    'somekey4' : 'data'
}};

Eventually this will be converted into JSON. So far I have tried using a dictionary like this:

connect.Method = "connect";
                connect.Data = new Dictionary<string, object>();
                connect.Data.Add("data", new Dictionary<string, object>()
                {
                { "somekey", "data" },
                { "somekey2", "data" },
                { "somekey3", "data" },
                { "somekey4", "data" }
                }
                );

but doing that in the json output it looks like:

{ "Method":"connect", "Data":{ "data":{ "somekey":"data", "somekey2":"data", "somekey3":"data", "somekey4":"data"} } }

Which is problematic because the M in method shouldn't be capitalized (its that way because how I defined the class I am sure I can fix this one myself.

The main issue is the extra "Data" that is getting added into the JSON.

Does anyone have any ideas of a better way to do this, I am trying to avoid just using huge strings to convert into JSON.

ZCT
  • 181
  • 1
  • 1
  • 13
  • 1
    why don't you simply use anonymous types? e.g. `var o = new { Method = "connect", Data = new { ... } };` (and serializer convention for the casing) – typesafe Nov 24 '19 at 18:47
  • How would that result in "Data" not being included when the object is serialized? – ZCT Nov 24 '19 at 18:49
  • Does this answer your question? [ASP.NET Core 3.0 System.Text.Json Camel Case Serialization](https://stackoverflow.com/questions/58476681/asp-net-core-3-0-system-text-json-camel-case-serialization) – jaspenlind Nov 24 '19 at 18:51
  • Take a look at [How do I serialize a C# anonymous type to a JSON string?](https://stackoverflow.com/a/10524654/3744182) plus [How can I return camelCase JSON serialized by JSON.NET from ASP.NET MVC controller methods?](https://stackoverflow.com/q/19445730/3744182). – dbc Nov 24 '19 at 18:53
  • What is this `connect` object? Why are you using it? Why not just do `var obj = new { method = "connect", data = { somekey = "data" /* ... */ } };` and return that? If `connect` represents your data model it would appear your data model doesn't match your desired JSON. – dbc Nov 24 '19 at 18:55

1 Answers1

0

In your C# code you create 2 dictionaries inside each other. That's why you get the extra levels in the structure.

You could eliminate one level by doing this

connect.Method = "connect";
connect.Data = new Dictionary<string, object>
{
  { "somekey", "data" },
  { "somekey2", "data" },
  { "somekey3", "data" },
  { "somekey4", "data" }
};

As for having lower case variable names, you can add the JsonProperty attribute to the fields. Here are the docs: https://www.newtonsoft.com/json/help/html/JsonPropertyName.htm

Hans Kilian
  • 18,948
  • 1
  • 26
  • 35