1

I have a string stream returning JSON data from and API that looks like this:

"{\"Recs\": 
[
   {\"EID\":\"F67_24_6\",\"ReturnPeriod\":\"1\",\"GageStation\":\"NA\"}, 
   {\"EID\":\"T67_24_6\",\"ReturnPeriod\":\"2.37\",\"GageStation\":\"Magueyes Island\"}, 
   {\"EID\":\"R67_24_6\",\"ReturnPeriod\":\"1\",\"GageStation\":\"50147800\"}
]}"

I am trying to deserialize it to return this:

{"Recs":[
          {"EID":"F67_24_6","ReturnPeriod":"1","GageStation":"NA"}, 
          {"EID":"T67_24_6","ReturnPeriod":"2.37","GageStation":"Magueyes Island"},     
          {"EID":"R67_24_6","ReturnPeriod":"1","GageStation":"50147800"}
]}

I am using these public classes to structure the return:

public class New_Events_Dataset
{
    public string EID { get; set; }
    public string ReturnPeriod { get; set; }
    public string GageStation { get; set; }

}

public class NewRootObject
{
    public List<New_Events_Dataset> Reqs { get; set; }
}

When I try to apply this later, I basically get a return of {"Reqs":null}. What am I doing wrong here?

var jsonResponse = JsonConvert.DeserializeObject<NewRootObject>(strresult);
string json = new JavaScriptSerializer().Serialize(jsonResponse);
return json;
3
  • 3
    You have "Reqs" as the name of the public List property in your root object class, is that intended? The name of the corresponding property in the JSON string appears to be "Recs" Commented Aug 27, 2019 at 20:09
  • Why are you using JsonConvert together with JavascriptSerialzer? Commented Aug 27, 2019 at 20:11
  • 2
    What Net framework are you using? Try using Net Core, the conversion to JSON is automatic. Commented Aug 27, 2019 at 20:12

2 Answers 2

5

I think Reqs should be Recs:

     public class NewRootObject
    {
         public List<New_Events_Dataset> Reqs { get; set; }
    }

try:

    public class NewRootObject
    {
         public List<New_Events_Dataset> Recs { get; set; }
     }
Sign up to request clarification or add additional context in comments.

Comments

2

Rename Reqs to Recs and create default constructor of class and instantiate Recs list

public class NewRootObject
{
    List<New_Events_Dataset> Recs { get; set; }

    public NewRootObject()
    {
        Recs = new List<New_Events_Dataset>();
    }
}

2 Comments

Nicer solution with instantiation of the List property
Arghhhh! That was totally it! Thanks for the nested NewRootObject function. That worked nicely.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.