0

I have some JSON coming back from an API as follows that I need to parse into an array of some other workable object:

{
    "Patients": [
        {
            "ChartNumber": "U1EQ643",
            "DateOfBirth": {
                "Raw": "19940704",
                "Value": null
            },
            "FirstName": "Joe",
            "LastName": "Smith",
            "MiddleName": null,
            "Sex": "M",
            "SocialSecurityNumber": {
                "Formatted": "xxx-xx-xxxx",
                "Raw": "xxxxxxxxx"
            }
        },
        {
            "ChartNumber": "abcQ643",
            "DateOfBirth": {
                "Raw": "19910614",
                "Value": null
            },
            "FirstName": "Alison",
            "LastName": "Smith",
            "MiddleName": null,
            "Sex": "F",
            "SocialSecurityNumber": {
                "Formatted": "xxx-xx-xxxx",
                "Raw": "xxxxxxxxx"
            }
        },
}

Here's what I have so far in my code:

class Svc1
{
    public void TrySearch2()
    {
        string URL = "https://SOMEWHERE.com/search";

        WebRequest request = WebRequest.Create(URL);

        request.Method = "POST";
        request.ContentType = "application/json; charset=utf-8";

        string searchFor = "smith";
        string postData = "{\"Authentication\": {\"SubscriberKey\": \"ABC\"," +
                                                "\"SiteServiceKey\": \"DEF\"}," +
                                                "\"" + requestType + "\": \"" + searchFor + "\"}";

        //get a reference to the request-stream, and write the postData to it
        using (Stream s = request.GetRequestStream())
        {
            using (StreamWriter sw = new StreamWriter(s))
                sw.Write(postData);
        }

        //get response-stream, and use a streamReader to read the content
        using (Stream s = request.GetResponse().GetResponseStream())
        {
            using (StreamReader sr = new StreamReader(s))
            {
                var jsonData = sr.ReadToEnd();

                var ds = new DataContractJsonSerializer(typeof(Patient[]));
                var msnew = new MemoryStream(Encoding.UTF8.GetBytes(jsonData));
                Patient[] items = (Patient[])ds.ReadObject(msnew);

            }
        }

    }

//patient class
[Serializable]
public class Patient
{
    private string _chartNumber;
    private string _dateOfBirth;
    private string _firstName;
    private string _lastName;
    private string _middleName;
    private string _sex;
    private string _ssNum;

    public Patient(string chartNo, string DOB, string first, string last, string middle, string sex, string SSNum)
    {
        this._chartNumber = chartNo;
        this._dateOfBirth = DOB;
        this._firstName = first;
        this._lastName = last;
        this._middleName = middle;
        this._sex = sex;
        this._ssNum = SSNum;
    }
    public string chartNumber
    {
        get { return _chartNumber; }
        set { _chartNumber = value; }
    }
    public string dateOfBirth
    {
        get { return _dateOfBirth; }
        set { _dateOfBirth = value; }
    }
    public string firstName
    {
        get { return _firstName; }
        set { _firstName = value; }
    }
    public string lastName
    {
        get { return _lastName; }
        set { _lastName = value; }
    }
    public string middleName
    {
        get { return _middleName; }
        set { _middleName = value; }
    }
    public string sex
    {
        get { return _sex; }
        set { _sex = value; }
    }
    public string SSNumber
    {
        get { return _ssNum; }
        set { _ssNum = value; }
    }
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
Beau D'Amore
  • 3,174
  • 5
  • 24
  • 56
  • DataContractJsonSerializer(as given in the code you've posted) would do the job for you. Not sure what else you're looking for. – aquaraga Apr 23 '13 at 18:03
  • You could also make use of the dynamic data type. Take look at this SO post http://stackoverflow.com/questions/3142495/deserialize-json-into-c-sharp-dynamic-object – Pete Garafano Apr 23 '13 at 18:09
  • 1
    Try JSON.NET, I used it a lot: http://james.newtonking.com/projects/json-net.aspx – Eugene Gordin Apr 23 '13 at 18:16
  • Thanks all, but I need some code, not English. What am I doing wrong? Aything? Or do I not realize I have what I need? I'm used to recordsets and arrays. – Beau D'Amore Apr 23 '13 at 19:19
  • i agree with eugene JSON.net makes deserializing JSON almost completly trivial you can general deserialize a json object in as little as a few lines of code – Chris McGrath Apr 23 '13 at 19:55
  • possible duplicate of [Parse JSON in C#](http://stackoverflow.com/questions/1212344/parse-json-in-c-sharp) – Dan Esparza Apr 23 '13 at 19:56
  • http://james.newtonking.com/projects/json/help/?topic=html/SerializingJSON.htm here is an example of using JSON.net – Chris McGrath Apr 23 '13 at 19:58

2 Answers2

1

From the Json you provided, I think you need a class that contains property Patients

public class ListOfPatients
{
    public ListOfPatinets(){Patients = new List<Patinent>();}

    public List<Patient> Patients{get;set;}
}

and then from your Json deserialize object of that new class

  var ds = new DataContractJsonSerializer(typeof(ListOfPatients));
  var msnew = new MemoryStream(Encoding.UTF8.GetBytes(jsonData));
  ListOfPatients list = (ListOfPatients)ds.ReadObject(msnew);
  var patients = list.Patients;
  .....

And I believe you need a default constructor in Patient class, and not sure if DataContractSerializer is case sensitive when matching Json to object properties. In Json you have "ChartNumber" and in the Patient class you have "chartNumber", that could cause problems but im not sure.

Jurica Smircic
  • 6,117
  • 2
  • 22
  • 27
1

Please put DataMember attribute on every property of your Parent class.

One more thing, the class structure you defined is not as per json you mentioned.

dateofBirth and SocialSecurityNumbers are also object and you are treating it as a string in the Parent class.

sohail.hussain.dyn
  • 1,411
  • 1
  • 16
  • 26
  • Yes, I had a coworker tell me that shortly after my post. All is well now. I synced up the class structure with the JSON and all is well with the world... – Beau D'Amore Apr 24 '13 at 20:13