I am working on Rest api. It is working fine. When i request it, it sends me a response. Actually this response is an array consisting of sub array and further key:value pairs in them. Now i want to extract these key:value pairs in C#. I thought of regex to extract substring but i have no knowledge of regex yet. but i tried to first get the sub array like.
Input string is
[
{
"id": "1",
"name": "kashif",
"father_name": "mirza",
"contact": "21321",
"email": "sdf",
"image": "sdfsdf"
},
{
"id": "2",
"name": "Kashif",
"father_name": "Mirza",
"contact": "0342809211",
"email": "[email protected]",
"image": "photo[1].jpg"
},
{
"id": "3",
"name": "Abdussadiq",
"father_name": "Abdul Haq Khan",
"contact": "03449066113",
"email": "[email protected]",
"image": "1393602_698558840157121_1872079026_n.jpg"
}
]
C# code for regex
Match match = Regex.Match(input, @"(?<=\{)(.*)(?=\})",
RegexOptions.IgnoreCase);
if (match.Success)
{
foreach(var matchgroup in match.Groups)
Console.WriteLine(matchgroup);
}
It returns me the result but not according to my needs. It returns me like
"id": "1",
"name": "kashif",
"father_name": "mirza",
"contact": "21321",
"email": "sdf",
"image": "sdfsdf"
},
{
"id": "2",
"name": "Kashif",
"father_name": "Mirza",
"contact": "0342809211",
"email": "[email protected]",
"image": "photo[1].jpg"
},
{
"id": "3",
"name": "Abdussadiq",
"father_name": "Abdul Haq Khan",
"contact": "03449066113",
"email": "[email protected]",
"image": "1393602_698558840157121_1872079026_n.jpg"
So that means it is removing the the just outer brackets but not the inner ones.
So my questions are:
You don't have to use regex for that.
The data you're trying to parse are in JSON format.
For example, you could parse it with Json.NET
Dictionary<string, dynamic> MyData = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(JsonData);
If you want a native support, try JavascriptSerializer (it also gives you an example of how to parse it directly into classes, which is better than dictionary regarding on your JSON data structure)
Dictionary<string, dynamic> MyData = JavaScriptSerializer.Deserialize<Dictionary<string, dynamic>>(JsonData);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With