Ajay
Ajay

Reputation: 6590

Retrieve the values from json string

I have json string. I want to retrieve the contact from json string. Following json contains array of contacts. here is my json string.

{
   "contacts": {
      "contact": [
         {
            "isConnection": false,
            "id": 33554611,
            "fields": [
               {
                  "id": 33554748,
                  "type": "name",
                  "value": {
                     "givenName": "Jhon",
                     "middleName": "",
                     "familyName": "Scot",
                     "prefix": "",
                     "suffix": "",
                     "givenNameSound": "",
                     "familyNameSound": ""
                  },
                  "editedBy": "OWNER",
                  "flags": [],
                  "categories": [],
                  "updated": "2012-12-23T07:40:23Z",
                  "created": "2012-12-23T07:40:23Z",
               },
               {
                  "id": 33554749,
                  "type": "email",
                  "value": "[email protected]",
                  "editedBy": "OWNER",
                  "flags": [],
                  "categories": [],
                  "updated": "2012-12-23T07:40:23Z",
                  "created": "2012-12-23T07:40:23Z",
               }
            ]
         }
    }
}

Here I want to retrieves the values of givenName,familyName,email. How can I retrieve the values of these from json string.

Note: there are array of contact in json. I have posted only one contact from this json.

I tried something like this. But not worked.

JObject json = JObject.Parse(returnStr);
JArray fields = (JArray)json["contacts"]["contact"]["fields"][0];
JArray FValues = (JArray)json["contact"]["fields"]["value"];

I tried this

public class Field
    {
        public int id { get; set; }
        public string type { get; set; }
        public object value { get; set; }
        public string editedBy { get; set; }
        public List<object> flags { get; set; }
        public List<object> categories { get; set; }
        public string updated { get; set; }
        public string created { get; set; }
        public string uri { get; set; }
        public bool? isConnection { get; set; }
    }

    public class contact
    {
        public bool isConnection { get; set; }
        public int id { get; set; }
        public List<Field> fields { get; set; }
        public List<object> categories { get; set; }
        public int error { get; set; }
        public int restoredId { get; set; }
        public string created { get; set; }
        public string updated { get; set; }
        public string uri { get; set; }
    }

    public class Contacts
    {
        public List<contact> contact { get; set; }
        public int count { get; set; }
        public int start { get; set; }
        public int total { get; set; }
        public string uri { get; set; }
        public bool cache { get; set; }
    }

    public class RootObject
    {
        public Contacts contacts { get; set; }
    }

and

JavaScriptSerializer serializer1 = new JavaScriptSerializer();
RootObject obje = serializer1.Deserialize<RootObject>(returnStr);

But it is giving me 0 value in obje.

Upvotes: 0

Views: 593

Answers (5)

HadiRj
HadiRj

Reputation: 1015

  1. First make sure your Json is in valid format using jsonlint

  2. Then generate class base on it using json2csharp

    public class Field
    {
        public int id { get; set; }
        public string type { get; set; }
        public object value { get; set; }
        public string editedBy { get; set; }
        public List<object> flags { get; set; }
        public List<object> categories { get; set; }
        public string updated { get; set; }
        public string created { get; set; }
    }
    
    public class Contact
    {
        public bool isConnection { get; set; }
        public int id { get; set; }
        public List<Field> fields { get; set; }
    }
    
    public class Contacts
    {
        public List<Contact> contact { get; set; }
    }
    
    public class RootObject
    {
        public Contacts contacts { get; set; }
    }
    
  3. Use Newtonsoft JSON to deserialize your Json into object(s) then you may simply access its properties value.

    JsonConvert.DeserializeObject<RootObject>(string json);
    

Upvotes: 3

joehanna
joehanna

Reputation: 1489

Firstly, I think you'll find that your JSON is not well-formed. You don't need the extra commas after the two "created" dates and there is a right-square bracket missing before the second last curly brace. I recommend you always validate your JSON using this awesome site: http://jsonformatter.curiousconcept.com

Secondly, you are not referencing the array elements correctly. Although I agree with @grundy that you should be creating class definitions for managing JSON and using LINQ, there is absolutely nothing wrong with the Newtonsoft library. You can still persist with your method.

Try this:-

var json = JObject.Parse(returnStr);
var fields = (JArray)json["contacts"]["contact"][0]["fields"];

var givenName = fields[0]["value"]["givenName"];
var familyName = fields[0]["value"]["familyName"];
var email = fields[1]["value"];

Upvotes: 0

Jason Jong
Jason Jong

Reputation: 4330

If you want to stick to JObject and not create classes, look at the example provided at http://weblog.west-wind.com/posts/2012/Aug/30/Using-JSONNET-for-dynamic-JSON-parsing

You'll have to enumerate over this

dynamic contacts = (JArray)json["contacts"]
foreach(dynamic contact in contacts.contact) {
   // look at the fields... 
}

PS. Give it a go, don't have VS on me so cant quite verify the exact syntax

Upvotes: 0

Amit Kumar Ghosh
Amit Kumar Ghosh

Reputation: 3726

You need to go with the following structure:

public class Contact
    {
        public bool isConnection { get; set; }
        public int id { get; set; }
        public List<Field> fields { get; set; }
    }
public class Field
{
    public int id { get; set; }
    public string type { get; set; }
    public object value { get; set; }
    public string editedBy { get; set; }
    public string[] flags { get; set; }
    public string[] categories { get; set; }
    public DateTime updated { get; set; }
    public DateTime created { get; set; }
}

public class Name
{
    public string givenName { get; set; }
    public string middleName { get; set; }
    public string familyName { get; set; }
    public string prefix { get; set; }
    public string suffix { get; set; }
    public string givenNameSound { get; set; }
    public string familyNameSound { get; set; }
}

And then deserialize it and use LINQ to manipulate fields.

Upvotes: 1

Matteo Umili
Matteo Umili

Reputation: 4017

Class for json object (generated with http://jsonutils.com/ after correcting some syntax error):

public class Field
{
    public int id { get; set; }
    public string type { get; set; }
    public object value { get; set; }
    public string editedBy { get; set; }
    public IList<object> flags { get; set; }
    public IList<object> categories { get; set; }
    public DateTime updated { get; set; }
    public DateTime created { get; set; }
}

public class Contact
{
    public bool isConnection { get; set; }
    public int id { get; set; }
    public IList<Field> fields { get; set; }
}

public class Contacts
{
    public IList<Contact> contact { get; set; }
}

public class Example
{
    public Contacts contacts { get; set; }
}

Deserialization (you will probably need to add a reference to System.Web.Extensions):

System.Web.Script.Serialization.JavaScriptSerializer deSer = new System.Web.Script.Serialization.JavaScriptSerializer();
JSonPrintSettingsToXml.Input.Example deserializedJSON = deSer.Deserialize<JSonPrintSettingsToXml.Input.Example>(yourJSON);

Here is the corrected JSON

{
    "contacts": {
        "contact": [
            {
                "isConnection": false,
                "id": 33554611,
                "fields": [
                    {
                        "id": 33554748,
                        "type": "name",
                        "value": {
                            "givenName": "Jhon",
                            "middleName": "",
                            "familyName": "Scot",
                            "prefix": "",
                            "suffix": "",
                            "givenNameSound": "",
                            "familyNameSound": ""
                        },
                        "editedBy": "OWNER",
                        "flags": [],
                        "categories": [],
                        "updated": "2012-12-23T07:40:23Z",
                        "created": "2012-12-23T07:40:23Z"
                    },
                    {
                        "id": 33554749,
                        "type": "email",
                        "value": "[email protected]",
                        "editedBy": "OWNER",
                        "flags": [],
                        "categories": [],
                        "updated": "2012-12-23T07:40:23Z",
                        "created": "2012-12-23T07:40:23Z"
                    }
                ]
            }
        ]
    }
}

Upvotes: 3

Related Questions