简体   繁体   中英

How to read a string array in appSettings.json?

My env is VSCode and NetCore 2.0.

I need to read a status code and several pairs of code/message from my appsetting.json.

This is my appsettings.json file

{
  "http": 
  {
    "statuscode": 200
  },
  "responses": 
  {
    "data": [
      {
        "code": 1,
        "message": "ok"
      },
      {
        "code": 2,
        "message": "erro"
      }
    ]
  }
}

I'm loading the configuration file and data like below, but everything is null:

private readonly IConfiguration _conf;
const string APPSET_SEC = "responses";
const string APPSET_KEY = "data";

public ValuesController(IConfiguration configuration)
{
_conf = configuration;

var section = _conf.GetSection($"{APPSET_SEC}:{APPSET_KEY}");
var responses = section.Get<string[]>();

var someArray = _conf.GetSection(APPSET_SEC).GetChildren().Select(x => x.Value).ToArray();

}

Either responses and someArray are null. It appears that the string array is not valid but it looks like a valid Json string array. What do I need to modify my appsettings or my C# code to get "data" array loaded into the variable?

I tryed a more simplificated array in json file

{
    "statuscode": 200,
    "data": [
      {
        "code": 1,
        "message": "ok"
      },
      {
        "code": 2,
        "message": "erro"
      }
    ]
 }

using the code:

var section = _conf.GetSection($"{APPSET_SEC}");
var responses = section.Get<string[]>();

but I still got no joy

You are trying to get it as a string array string[] when it is an object array,

Create a POCO model to match the setting

public class ResponseSeting {
    public int code { get; set; }
    public string message { get; set; }
}

and get an array of that.

So given the following appsetting.json

{
  "http": 
  {
    "statuscode": 200
  },
  "responses": 
  {
    "data": [
      {
        "code": 1,
        "message": "ok"
      },
      {
        "code": 2,
        "message": "erro"
      }
    ]
  }
}

The response data would be extracted like

var responses = Configuration
    .GetSection("responses:data")
    .Get<ResponseSeting[]>();

This can be done in java using rest-assured library

JSON.body("http.statuscode") --> Will get the statuscode

JSON.body(responses.data.code[0]) --> will get the response code
JSON.body(responses.data.message[0])---> will get the response message
JSON.body(responses.data.code[1])
JSON.body(responses.data.message[1])

Ain't got a scoobydo on how VScode works. But long story short, this might help you!!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM