-1

I have int appsettings.js section like that:

 "AccessKeys": {
    "user1": {
      "pass": ""
    },

I created classes in C# to bind this section to these classes:

public class AccessKeys { public List Users = new List(); }

public class AccessKeyUserJson
{
    public AccessKeyUser AccessKeyUser { get; set; }
}

public class AccessKeyUser
{
    public string Pass { get; set; }
}

I bind above classes in Startup.cs:

  services.Configure<AppSettingsConfig>(Configuration);

In AppSettingsConfig I have property AccessKeys and this property is binded correctly but Users is empty (0 items)


I changed structure:

"AccessKeys": [
    {
      "user1": "",
      "pass": ""
    },
]
Robert
  • 2,571
  • 10
  • 63
  • 95
  • 1
    `AccessKeyUserJson` need a method named `user1`. If you need an array try with `"AccessKey": [ { "user1": ....}, { "user2": ....}, ]` and then use a property array `AccessKeyUser[]` – Fabio Nov 30 '20 at 13:00
  • Obviously because there is no `Users` in `AccessKeys` ... It looks more like dictionary not list ... so basically your model is different than json content – Selvin Nov 30 '20 at 13:12

1 Answers1

-1

Why don't you try something like this:

using (var ms = new System.IO.MemoryStream(Encoding.Unicode.GetBytes(myJSONstring)))
{
    System.Runtime.Serialization.Json.DataContractJsonSerializer js = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(myStruct));
    myStruct aux = (myStruct)js.ReadObject(ms);
}

This is a single level approach, and sincerely, I've never tried to cast anything in a sub-classing scheme but maybe it worths trying.

As you can see, here, the JSON string is taken by a Memory Stream and then casted into the final struct/class.

Carles
  • 418
  • 2
  • 18
  • it's about [app settings](https://learn.microsoft.com/en-US/aspnet/core/fundamentals/configuration/) not general json parsing – Selvin Nov 30 '20 at 13:09