Ali
Ali

Reputation: 1225

Replace String with Array of Objects

I am trying to replace a string constant with an array of object.

What I have is

string test = "{\"property\":\"#replacedValue#\"}";

var array = someObject.where(x=>something).ToArray();

test = test.Replace("#replacedValue#",JsonConvert.SerializeObject(array));

output is coming as

{"property":"[{"name":"value"},{"name":"value"},{"name":"value"}]"}

Array is being replaced as string

what I want is

 {"property":[{"name":"value"},{"name":"value"},{"name":"value"}]};

I am using .net core 3.1

Upvotes: 0

Views: 383

Answers (1)

Guru Stron
Guru Stron

Reputation: 142853

You can parse your json string into JObject and replace property value:

string test = @"{""property"":""#replacedValue#""}";

var jObj = JsonConvert.DeserializeObject<JObject>(test);
jObj["property"] = new JArray(new[] {1,2,3,4});
Console.WriteLine(jObj.ToString());

will print:

{
  "property": [
    1,
    2,
    3,
    4
  ]
}

Upvotes: 2

Related Questions