Converting string to JArray

Asked by At

I have to use an API that expects a string containing a an array of json objects.

internal string InitConnect( string RequestData )
        dynamic filejsonJarray = new JArray();
        filejsonJarray = JArray.Parse(RequestData);
        JObject jsonObject = (JObject)filejsonJarray.First;

        if (jsonObject.ContainsKey("IP_ADDRESS".ToUpper()))

In my code I tried different ways of calling this API but don't seem to be able to get the argument right. I have to create an object (connData) using data I have read from a config file (sJSONConfig) and use it as an argument to API; last thing I tried:

string sJSONConfig = Global.ReadJsonConfig(); 
// returns"{\r\n  \"Name\": \"BLAH\",\r\n  \"IPAddress\": \"\",\r\n  \"Port\": \"5880\"\r\n}"

JArray filejsonJarray = new JArray();

JObject jsonObject = new JObject();
jsonObject = JObject.Parse(sSJONConfig);
//filejsonJarray = JArray.Parse(sSJONConfig);
//jsonObject = (JObject)filejsonJarray.First;

// Reconnect using new config data
var connData = new
    NAME = jsonObject.Property("Name").Value.ToString(),
    IP_ADDRESS = jsonObject.Property("IPAddress").Value.ToString(),
    PORT = jsonObject.Property("Port").Value.ToString(),
    Enabled = "true",
    Something = "false"

string reqData = JsonConvert.SerializeObject(filejsonJarray);

Obviously, I cannot changed the InitConnect API.

1 Answers

Brian Rogers On Best Solutions

You can create your desired JSON like this:

string sJSONConfig = Global.ReadJsonConfig();

JObject jsonObject = JObject.Parse(sJSONConfig);

JObject connData = new JObject(
    new JProperty("NAME", jsonObject["Name"]),
    new JProperty("IP_ADDRESS", jsonObject["IPAddress"]),
    new JProperty("PORT", jsonObject["Port"]),
    new JProperty("Enabled", "true"),
    new JProperty("Something", "false")

JArray filejsonJarray = new JArray(connData);

string reqData = filejsonJarray.ToString();