0

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

3
  • 4
    JSON is a string format. The problem here is you're replacing only the #replacedValue# value, leaving the surrounding quotes in place. Replace the entire string instead ("#replacedValue#") escaping the double quotes Commented Jul 14, 2020 at 11:32
  • string test = {"property":"#replacedValue#"}; this is not valid C#. What your probably have is string test = "{\"property\":\"#replacedValue#\"}"; Commented Jul 14, 2020 at 11:39
  • code updated with valid string. Commented Jul 14, 2020 at 11:45

1 Answer 1

2

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
  ]
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.