简体   繁体   中英

Generate C# object from Json string and parse Json string to generated object

I am trying to generate C# class using the JSON string from here http://json2csharp.com/ this works fine. But I can't parse the JSON to the object generated by the website.

Here is the JSON string

{
  "searchParameters":{
    "key":"**********",
    "system":"urn:oid:.8"
  },
  "message":" found one Person matching your search criteria.",
  "_links":{
    "self":{
      "href":"https://integration.rest.api.test.com/v1/person?key=123456&system=12.4.34.."
    }
  },
  "_embedded":{
    "person":[
      {
        "details":{
          "address":[
            {
              "line":["5554519 testdr"],
              "city":"testland",
              "state":"TT",
              "zip":"12345",
              "period":{
                "start":"2003-10-22T00:00:00Z",
                "end":"9999-12-31T23:59:59Z"
              }
            }
          ],
          "name":[
            {
              "use":"usual",
              "family":["BC"],
              "given":["TWO"],
              "period":{
                "start":"9999-10-22T00:00:00Z",
                "end":"9999-12-31T23:59:59Z"
              }
            }
          ],
          "gender":{
            "code":"M",
            "display":"Male"
          },
          "birthDate":"9999-02-03T00:00:00Z",
          "identifier":[
            {
              "use":"unspecified",
              "system":"urn:oid:2.19.8",
              "key":"",
              "period":{
                "start":"9999-10-22T00:00:00Z",
                "end":"9999-12-31T23:59:59Z"
              }
            }
          ],
          "telecom":[
            {
              "system":"email",
              "value":"test@test.com",
              "use":"unspecified",
              "period":{
                "start":"9999-10-22T00:00:00Z",
                "end":"9999-12-31T23:59:59Z"
              }
            }
          ],
          "photo":[
            {
              "content":{
                "contentType":"image/jpeg",
                "language":"",
                "data":"",
                "size":0,
                "hash":"",
                "title":"My Picture"
              }
            }
          ]
        },
        "enrolled":true,
        "enrollmentSummary":{
          "dateEnrolled":"9999-02-07T21:39:11.174Z",
          "enroller":"test Support"
        },
        "_links":{
          "self":{
            "href":"https://integration.rest.api.test.com/v1/person/-182d-4296-90cc"
          },
          "unenroll":{
            "href":"https://integration.rest.api.test.com/v1/person/1b018dc4-182d-4296-90cc-/unenroll"
          },
          "personLink":{
            "href":"https://integration.rest.api.test.com/v1/person/-182d-4296-90cc-953c/personLink"
          },
          "personMatch":{
            "href":"https://integration.rest.api.commonwellalliance.org/v1/person/-182d-4296-90cc-/personMatch?orgId="
          }
        }
      }
    ]
  }
}

Here is the code I use to convert to the object.

JavaScriptSerializer js = new JavaScriptSerializer();
 var xx = (PersonsearchVM)js.Deserialize(jsonstr, typeof(PersonsearchVM));

Is there any other wat to generate the object and parse?

I think you have some invalid characters in your JSON string. Run it through a validator and add the necessary escape characters.

http://jsonlint.com/

You aren't casting it to the right object. Cast it to the type RootObject.

Eg

JavaScriptSerializer js = new JavaScriptSerializer();
var xx = (RootObject)js.Deserialize(jsonstr, typeof(RootObject));

The code that json 2 csharp creates is this:

public class SearchParameters
{
    public string key { get; set; }
    public string system { get; set; }
}

    public class Self
{
    public string href { get; set; }
}

public class LinKs
{
    public Self self { get; set; }
}

public class Period
{
    public string start { get; set; }
    public string end { get; set; }
}

public class Address
{
    public List<string> line { get; set; }
    public string city { get; set; }
    public string __invalid_name__state { get; set; }
    public string zip { get; set; }
    public Period period { get; set; }
}

public class PerioD2
{
    public string start { get; set; }
    public string end { get; set; }
}

public class Name
{
    public string use { get; set; }
    public List<string> family { get; set; }
    public List<string> given { get; set; }
    public PerioD2 __invalid_name__perio
d { get; set; }
}

public class Gender
{
    public string __invalid_name__co
de { get; set; }
    public string display { get; set; }
}

public class Period3
{
    public string start { get; set; }
    public string __invalid_name__end { get; set; }
}

public class Identifier
{
    public string use
 { get; set; }
    public string system { get; set; }
    public string key { get; set; }
    public Period3 period { get; set; }
}

public class Period4
{
    public string start { get; set; }
    public string end { get; set; }
}

public class Telecom
{
    public string system { get; set; }
    public string value { get; set; }
    public string use { get; set; }
    public Period4 period { get; set; }
}

public class Content
{
    public string contentType { get; set; }
    public string language { get; set; }
    public string __invalid_name__dat
a { get; set; }
    public int size { get; set; }
    public string hash { get; set; }
    public string title { get; set; }
}

public class Photo
{
    public Content content { get; set; }
}

public class Details
{
    public List<Address> address { get; set; }
    public List<Name> name { get; set; }
    public Gender gender { get; set; }
    public string birthDate { get; set; }
    public List<Identifier> identifier { get; set; }
    public List<Telecom> telecom { get; set; }
    public List<Photo> photo { get; set; }
}

public class EnrollmentSummary
{
    public string dateEnrolled { get; set; }
    public string __invalid_name__en
roller { get; set; }
}

public class Self2
{
    public string href { get; set; }
}

public class UnEnroll
{
    public string href { get; set; }
}

public class PersonLink
{
    public string href { get; set; }
}

public class PersonMatch
{
    public string href { get; set; }
}

public class Links2
{
    public Self2 self { get; set; }
    public UnEnroll __invalid_name__un
enroll { get; set; }
    public PersonLink personLink { get; set; }
    public PersonMatch personMatch { get; set; }
}

public class Person
{
    public Details details { get; set; }
    public bool __invalid_name__e
nrolled { get; set; }
    public EnrollmentSummary enrollmentSummary { get; set; }
    public Links2 _links { get; set; }
}

public class Embedded
{
    public List<Person> person { get; set; }
}

public class RootObject
{
    public SearchParameters searchParameters { get; set; }
    public string message { get; set; }
    public LinKs __invalid_name___lin
ks { get; set; }
    public Embedded _embedded { get; set; }
}

The following function will convert JSON into a C# class where T is the class type.

public static T Deserialise<T>(string json)
{
    T obj = Activator.CreateInstance<T>();
    using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
    {
        DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
                obj = (T)serializer.ReadObject(ms); // 
                return obj;
    }
}

You need a reference to the System.Runtime.Serialization.json namespace.

The function is called in the following manner;

calendarList = Deserialise<GoogleCalendarList>(calendarListString);

calendarlist being the C# class and calendarListString the string containing the JSON.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM