super-user super-user - 4 months ago 24
JSON Question

C# String Remove First 2 Object in a JSON.Stringify

I have an MVC controller that accepts a json stringify object that looks like this:

[{\"name\":\"Name\",\"value\":\"1\"},
{\"name\":\"Mobile\",\"value\":\"2\"},
{\"name\":\"Gender\",\"value\":\"Male\"},
{\"name\":\"Birthdate\",\"value\":\"2016-07-13\"},
{\"name\":\"Address\",\"value\":\"3\"}]


And I want to remove the first 2 objects using a string function available in c# to look like this:

[{\"name\":\"Gender\",\"value\":\"Male\"},
{\"name\":\"Birthdate\",\"value\":\"2016-07-13\"},
{\"name\":\"Address\",\"value\":\"3\"}]`


How can I do this in the most simple way?

Answer

Using string-functions you could do following:

string s = "[{\"name\":\"Name\",\"value\":\"1\"}, {\"name\":\"Mobile\",\"value\":\"2\"}, {\"name\":\"Gender\",\"value\":\"Male\"}, {\"name\":\"Birthdate\",\"value\":\"2016-07-13\"}, {\"name\":\"Address\",\"value\":\"3\"}]";
string[] splitted = s.Split('{');
s = s.Replace("{" + splitted[1], "");
s = s.Replace("{" + splitted[2], "");

output:

[{"name":"Gender","value":"Male"}, 
{"name":"Birthdate","value":"2016-07-13"}, 
{"name":"Address","value":"3"}]