locked
Error while converting Json Result to .net class object RRS feed

  • Question

  • User-1266083892 posted

    Hi,

    I am getting the following json result from an api.

    {
      "Limit": 100,
      "Offset": 0,
      "TotalResults": 8181,
      "Locale": "en_US",
      "Results": [
        {
          "Id": "212832789",
          "CID": "3f06fa2a-9f90-594e-aa82-589e0238c42a",
          "SourceClient": "ditech",
          "LastModeratedTime": "2018-11-26T01:15:15.000+00:00",
          "LastModificationTime": "2018-11-26T01:15:15.000+00:00",
          "ProductId": "ditech-JULIA_BROWNELL-REFINANCE",
          "CampaignId": "BV_PIE",
          "AuthorId": "pdoifmawkx0wwadlgfvb62wff",
          "ContentLocale": "en_US",
          "IsFeatured": false,
          "TotalClientResponseCount": 0,
          "TotalCommentCount": 0,
          "Rating": 4,
          "SecondaryRatingsOrder": [
            "EaseOfObtainingLoan",
            "SpeedOfObtainingLoan",
            "Rate",
            "FeesClosingCosts",
            "CustomerService",
            "Responsiveness"
          ],
          "IsRatingsOnly": true,
          "TotalFeedbackCount": 0,
          "TotalNegativeFeedbackCount": 0,
          "TotalPositiveFeedbackCount": 0,
          "ModerationStatus": "APPROVED",
          "SubmissionId": "h8w1vmbs4p001nobdycx24ti3",
          "SubmissionTime": "2018-11-26T01:13:21.000+00:00",
          "UserNickname": null,
          "SecondaryRatings": {
            "EaseOfObtainingLoan": {
              "Value": 4,
              "Id": "EaseOfObtainingLoan",
              "ValueLabel": null,
              "MaxLabel": null,
              "DisplayType": "NORMAL",
              "Label": "Ease of Obtaining Loan",
              "ValueRange": 5,
              "MinLabel": null
            },
            "CustomerService": {
              "Value": 4,
              "Id": "CustomerService",
              "ValueLabel": null,
              "MaxLabel": null,
              "DisplayType": "NORMAL",
              "Label": "Customer Service",
              "ValueRange": 5,
              "MinLabel": null
            },
            "Responsiveness": {
              "Value": 5,
              "Id": "Responsiveness",
              "ValueLabel": null,
              "MaxLabel": null,
              "DisplayType": "NORMAL",
              "Label": "Responsiveness",
              "ValueRange": 5,
              "MinLabel": null
            },
            "FeesClosingCosts": {
              "Value": 3,
              "Id": "FeesClosingCosts",
              "ValueLabel": null,
              "MaxLabel": null,
              "DisplayType": "NORMAL",
              "Label": "Fees & Closing Costs",
              "ValueRange": 5,
              "MinLabel": null
            },
            "SpeedOfObtainingLoan": {
              "Value": 4,
              "Id": "SpeedOfObtainingLoan",
              "ValueLabel": null,
              "MaxLabel": null,
              "DisplayType": "NORMAL",
              "Label": "Speed of Obtaining Loan",
              "ValueRange": 5,
              "MinLabel": null
            },
            "Rate": {
              "Value": 3,
              "Id": "Rate",
              "ValueLabel": null,
              "MaxLabel": null,
              "DisplayType": "NORMAL",
              "Label": "Rate",
              "ValueRange": 5,
              "MinLabel": null
            }
          },
          "Helpfulness": null,
          "BadgesOrder": [],
          "IsSyndicated": false,
          "ProductRecommendationIds": [],
          "Badges": {},
          "Title": null,
          "Photos": [],
          "Pros": null,
          "IsRecommended": null,
          "RatingRange": 5,
          "Videos": [],
          "UserLocation": null,
          "TagDimensions": {},
          "AdditionalFieldsOrder": [],
          "Cons": null,
          "ContextDataValuesOrder": [],
          "TagDimensionsOrder": [],
          "AdditionalFields": {},
          "ContextDataValues": {},
          "ClientResponses": [],
          "CommentIds": [],
          "ReviewText": null
        },
        {
          "Id": "212825061",
          "CID": "faf05ed4-d0dc-5d78-bcb1-4d172a66afce",
          "SourceClient": "ditech",
          "LastModeratedTime": "2018-11-25T17:45:10.000+00:00",
          "LastModificationTime": "2018-11-25T17:45:10.000+00:00",
          "ProductId": "ditech-BAUDELAIRE_GUILLAUME-REFINANCE",
          "CampaignId": "BV_PIE",
          "AuthorId": "tla6kktnm0coa6qmrhbz4blss",
          "ContentLocale": "en_US",
          "IsFeatured": false,
          "TotalClientResponseCount": 0,
          "TotalCommentCount": 0,
          "Rating": 4,
          "SecondaryRatingsOrder": [
            "EaseOfObtainingLoan",
            "SpeedOfObtainingLoan",
            "Rate",
            "FeesClosingCosts",
            "CustomerService",
            "Responsiveness"
          ],
          "IsRatingsOnly": true,
          "TotalFeedbackCount": 0,
          "TotalNegativeFeedbackCount": 0,
          "TotalPositiveFeedbackCount": 0,
          "ModerationStatus": "APPROVED",
          "SubmissionId": "b0bxyti5n5wk8nah9dj3oobxw",
          "SubmissionTime": "2018-11-25T17:44:05.000+00:00",
          "UserNickname": "Gary",
          "SecondaryRatings": {
            "EaseOfObtainingLoan": {
              "Value": 4,
              "Id": "EaseOfObtainingLoan",
              "ValueLabel": null,
              "MaxLabel": null,
              "DisplayType": "NORMAL",
              "Label": "Ease of Obtaining Loan",
              "ValueRange": 5,
              "MinLabel": null
            },
            "CustomerService": {
              "Value": 4,
              "Id": "CustomerService",
              "ValueLabel": null,
              "MaxLabel": null,
              "DisplayType": "NORMAL",
              "Label": "Customer Service",
              "ValueRange": 5,
              "MinLabel": null
            },
            "Responsiveness": {
              "Value": 4,
              "Id": "Responsiveness",
              "ValueLabel": null,
              "MaxLabel": null,
              "DisplayType": "NORMAL",
              "Label": "Responsiveness",
              "ValueRange": 5,
              "MinLabel": null
            },
            "FeesClosingCosts": {
              "Value": 3,
              "Id": "FeesClosingCosts",
              "ValueLabel": null,
              "MaxLabel": null,
              "DisplayType": "NORMAL",
              "Label": "Fees & Closing Costs",
              "ValueRange": 5,
              "MinLabel": null
            },
            "SpeedOfObtainingLoan": {
              "Value": 4,
              "Id": "SpeedOfObtainingLoan",
              "ValueLabel": null,
              "MaxLabel": null,
              "DisplayType": "NORMAL",
              "Label": "Speed of Obtaining Loan",
              "ValueRange": 5,
              "MinLabel": null
            },
            "Rate": {
              "Value": 4,
              "Id": "Rate",
              "ValueLabel": null,
              "MaxLabel": null,
              "DisplayType": "NORMAL",
              "Label": "Rate",
              "ValueRange": 5,
              "MinLabel": null
            }
          },
          "Helpfulness": null,
          "BadgesOrder": [],
          "IsSyndicated": false,
          "ProductRecommendationIds": [],
          "Badges": {},
          "Title": null,
          "Photos": [],
          "Pros": null,
          "IsRecommended": null,
          "RatingRange": 5,
          "Videos": [],
          "UserLocation": null,
          "TagDimensions": {},
          "AdditionalFieldsOrder": [],
          "Cons": null,
          "ContextDataValuesOrder": [],
          "TagDimensionsOrder": [],
          "AdditionalFields": {},
          "ContextDataValues": {},
          "ClientResponses": [],
          "CommentIds": [],
          "ReviewText": null
        }
    ],
      "Includes": {},
      "HasErrors": false,
      "Errors": []
    }

    And my .net class structure is as follows

     public class ProductReviews
        {
            public string Id { get; set; }
            public string CID { get; set; }
            public string SourceClient { get; set; }
            public DateTime LastModeratedTime { get; set; }
            public DateTime LastModificationTime { get; set; }
            public string ProductId { get; set; }
            public string CampaignId { get; set; }
            public string AuthorId { get; set; }
            public string ContentLocale { get; set; }
            public bool IsFeatured { get; set; }
            public int TotalClientResponseCount { get; set; }
            public int TotalCommentCount { get; set; }
            public int Rating { get; set; }
    
            public List<string> SecondaryRatingsOrder { get; set; }
    
            public bool IsRatingsOnly { get; set; }
            public int TotalFeedbackCount { get; set; }
            public int TotalNegativeFeedbackCount { get; set; }
            public int TotalPositiveFeedbackCount { get; set; }
            public string ModerationStatus { get; set; }
            public string SubmissionId { get; set; }
            public DateTime SubmissionTime { get; set; }
            public string UserNickname { get; set; }
    
            public SecondaryRatings SecondaryRatings { get; set; }
    
            public List<object> BadgesOrder { get; set; }
            public bool IsSyndicated { get; set; }
            public List<object> ProductRecommendationIds { get; set; }
            public Badges Badges { get; set; }
            public string Title { get; set; }
            public List<object> Photos { get; set; }
            public object Pros { get; set; }
            public object IsRecommended { get; set; }
    
            public int RatingRange { get; set; }
            public List<object> Videos { get; set; }
            public object UserLocation { get; set; }
            public TagDimensions TagDimensions { get; set; }
            public List<object> AdditionalFieldsOrder { get; set; }
            public object Cons { get; set; }
            public List<object> ContextDataValuesOrder { get; set; }
            public List<object> TagDimensionsOrder { get; set; }
            public AdditionalFields AdditionalFields { get; set; }
            public ContextDataValues ContextDataValues { get; set; }
            public List<object> ClientResponses { get; set; }
            public List<object> CommentIds { get; set; }
            public string ReviewText { get; set; }
    
        }
    
        public class SecondaryRatings
        {
            public SecondaryRatingFields EaseOfObtainingLoan { get; set; }
            public SecondaryRatingFields CustomerService{ get; set; }
            public SecondaryRatingFields Responsiveness { get; set; }
            public SecondaryRatingFields FeesClosingCosts { get; set; }
            public SecondaryRatingFields SpeedOfObtainingLoan { get; set; }
            public SecondaryRatingFields Rate { get; set; }
        }
        public class SecondaryRatingFields
        {
            public string Value  { get;set;}
            public string Id { get;set;}
            public string ValueLabel  { get;set;}
            public string MaxLabel { get;set;}
            public string DisplayType { get;set;}
            public string Label { get;set;}
            public string ValueRange { get;set;}
            public string MinLabel { get;set;}
        }
        public class Badges
        {
        }
    
        public class TagDimensions
        {
        }
        public class AdditionalFields
        {
        }
    
        public class ContextDataValues
        {
        }

    I am getting the following error 

    Cannot deserialize the current JSON object (e.g. {"name":"value"})
    into type 'System.Collections.Generic.List`1[Test.Models.ProductReviews]'
    because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
    To fix this error either change the JSON to a JSON array (e.g. [1,2,3])
    or change the deserialized type so that it is a normal .NET type
    (e.g. not a primitive type like integer, not a collection type like an array or List<T>)
    that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
    Path 'Limit', line 1, position 9.

    The line where I am getting error is this

     if (response.IsSuccessStatusCode)
                    {
                        reviewList =  response.Content.ReadAsAsync<List<ProductReviews>>().Result;
                       
                    }

    Please help me

    Thanks,

    Priya

    Monday, November 26, 2018 8:07 AM

Answers

  • User753101303 posted

    Hi,

    Which is correct. The JSON you are showing is an object with the Results porperty being a list of reviews. Add the missing declaration for this root object and deserialize it.

    You can use tools such as http://json2csharp.com/ (or Quicktype) to generate C# code from a JSON payload.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, November 26, 2018 8:44 AM

All replies

  • User753101303 posted

    Hi,

    Which is correct. The JSON you are showing is an object with the Results porperty being a list of reviews. Add the missing declaration for this root object and deserialize it.

    You can use tools such as http://json2csharp.com/ (or Quicktype) to generate C# code from a JSON payload.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, November 26, 2018 8:44 AM
  • User-893317190 posted

    Hi priya.renjith,

    It seems List<ProductReviews> is only part of your json.

    So I suggest you could get string result first and use JToken to get part of your json and then DeserializeObject,

    Below is my code.

    api, json.json's content  is  your json.

     public object Get(int id)
            {
              string path=  System.Web.Hosting.HostingEnvironment.MapPath("~/TextFile1.txt");
               string result= File.ReadAllText(HttpContext.Current.Request.MapPath("/Controllers/json.json"));
              return   Newtonsoft.Json.JsonConvert.DeserializeObject(result);
               
            }

    client.

    protected void Page_Load(object sender, EventArgs e)
            {
                var client = new HttpClient();
    
                Task<string> task = client.GetStringAsync("http://localhost:55466/api/Values/1");
                 string result=   task.Result;
               
                JToken jobj = JToken.Parse(result);  //parse string to JToken
                  
               string results=jobj["Results"].ToString(); //get the results property of the JToken
               List<ProductReviews> reviews= JsonConvert.DeserializeObject<List<ProductReviews>>(results);// DeserializeObject resutls
    
                Response.Write(JsonConvert.SerializeObject(reviews));
    
            }

    The result.

    Best regards,

    Ackerly Xu

    Tuesday, November 27, 2018 6:25 AM