简体   繁体   中英

C# Rest Response in JSON Deserialize to Custom Object

I have reviewed a lot of posts about this question and I am still having trouble. I am using Newtonsoft.Json and the following code:

string url = @"https://https://someSite.com/indexes('myIndex')search=SEARCH_PHONES:";
string phoneNumber = "5550005555";
url += phoneNumber;

HttpWebRequest request = HttpWebRequest.CreateHttp(url);
request.Method = "GET";
request.Headers.Add("api-key", "####");
WebResponse response = request.GetResponse();
Stream imageStream = response.GetResponseStream();
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
StreamReader readStream = new StreamReader(imageStream, encode);
string s = readStream.ReadToEnd();

JObject joResponse = JObject.Parse(s);
JArray array = (JArray)joResponse["value"];
string customer = array[0].ToString();

The problem is that array is returning as one long string. How do I access the individual key/value pairs? Below is the response I recieve:

{
"@odata.context": "https://someSite.com/indexes('myIndex')/$metadata#docs",
"value": [
    {
        "@search.score": 10.933167,
        "CUSTOMER_DIM_ID": "77049309",
        "SOURCE_CUSTOMER_ID": null,
        "PORTSTORE_ID": "0326_1448401",
        "FIRST_NM": "First Name",
        "LAST_NM": "Last Name",
        "ADDR_LINE_1": "133 Main St",
        "ADDR_LINE_2": null,
        "CITY": "MyCity",
        "STATE_CD": "IL",
        "POSTAL_CD": "99999",
        "COUNTRY": "United States",
        "EMAIL_ADDR": "myEmail@gmail.com",
        "BIRTH_DT": null,
        "PHONE": "5550005555",
        "GENDER_CD": "F",
        "SEARCH_EMAILS": [
            "myEmail@gmail.com"
        ],
        "SEARCH_PHONES": [
            "5550005555"
        ],
        "JUS_EMAIL_OPTIN": true,
        "JCA_EMAIL_OPTIN": true,
        "LCA_EMAIL_OPTIN": true,
        "JUS_DM_OPTIN": true,
        "JCA_DM_OPTIN": true,
        "LCA_DM_OPTIN": true,
        "MOBILE_OPTIN": false,
        "LIFETIME_REVENUE": "138.1800",
        "LIFETIME_UNITS": 7,
        "NTH_ORDER": 2,
        "FIRST_PURCHASE_DT": "2016-02-11T00:00:00Z",
        "LAST_PURCHASE_DT": "2016-02-19T00:00:00Z",
        "AVG_LAG": 8,
        "IsDeleted": false,
        "UPDATE_DT": "2016-02-19T00:00:00Z"
    }
]

}

I don't have access to change the response. I tried to use json2sharp to create the objects and then simply deserialize but it said that the "@search.score" was invalid as well as "@odata.context". After I commented out those lines in my C# code it does not deserialize correctly (everything is null) I need to be able to retrieve the customer information and assign it to my custom class.

It looks like you're doing a little extra work here. Instead of

Stream imageStream = response.GetResponseStream();
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
StreamReader readStream = new StreamReader(imageStream, encode);
string s = readStream.ReadToEnd();

Do string s = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

Then, you can do a JsonConvert.DeserializeObject<MyType>(s) and that should get you your object.

Also in your object, make sure to use the appropriate serialization attributes wherever your names don't match up, if you wanted a particular naming style for example.

Don't manually parse through JSON unless you have a really good reason to do so.

Make a web request using your rest client of choice (postman/dhcp/etc.) and copy the response. Then create a new .cs file and go to Edit -> Past Special -> Paste Json as class.

From here you should get a mostly working POCO that can be used for deserializing the JSON using Newtonsoft.Json.JsonConvert.Deserialize<Class>(responseJson) .

Note that newtonsoft defaults to camel case for json properties. Since your properties are not camel case, you need to explicitly define the property name.

[JsonProperty("ID")]
public int ID { get; set; }

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