0

I am new to C# and trying to write some code to fetch the webpage and parse it into readable format.

I have fetched the data from webpage using uri

var uri2 = new Uri("explame.com")

I see the response in format below like this:

{"name":"abc" "country":"xyz" "citizenship":"A" [{"pincode":"111", "Dis":"no"] Lot's of data follows something like that

There are multiple with attribute "name" and "country" in response. My question is how to fetch the data something like below

name:abc
country:xyz
citizenshih:A
pincode 111
dis:no

For all attributes in response code.

louis
  • 595
  • 3
  • 9
  • 24
  • That's json, there are tons of parsers and even with a regex can be used, but stick with what tofutim said, Newtonsoft.Json, also known as Json.net – Gusman Mar 01 '16 at 17:34
  • Is that the *exact* format of the data you're getting? Because that's JSON-*ish*, but it's not valid JSON and wouldn't be parsed as such. – David Mar 01 '16 at 17:38
  • @tofutim Would you mind sharing a simple example on how to use Newtonsoft json for above example. Thanks! – louis Mar 01 '16 at 17:38
  • Possible duplicate of [How can I parse JSON with C#?](http://stackoverflow.com/questions/6620165/how-can-i-parse-json-with-c) – Rob Mar 01 '16 at 22:32

2 Answers2

1

Is that the exact format of the data you're getting? Because that's JSON-ish, but it's not valid JSON and wouldn't be parsed as such. If, however, you are actually getting JSON then you can de-serialize that.

Using something like Newtonsoft's JSON library you can fairly trivially de-serialize JSON into an object. For example, this JSON:

{
  "name":"abc",
  "country":"xyz",
  "citizenship":"A",
  "someProperty": [
    {
      "pincode":"111",
      "Dis":"no"
    }]
}

Might map to these types:

class MyClass
{
    public string Name { get; set; }
    public string Country { get; set; }
    public string Citizenship { get; set; }
    public IEnumerable<MyOtherClass> SomeProperty { get; set; }
}

class MyOtherClass
{
    public string Pincode { get; set; }
    public string Dis { get; set; }
}

In which case de-serializing might be as simple as this:

var myObject = JsonConvert.DeserializeObject<MyClass>(yourJsonString);
David
  • 208,112
  • 36
  • 198
  • 279
0

you could try

dynamic data = JsonConvert.DeserializeObject(receivedJsonString);
            foreach (dynamic o in data)
            {
                Debug.WriteLine(o.country);
            }
profesor79
  • 9,213
  • 3
  • 31
  • 52