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" Aug 27, 2019 at 20:09
  • Why are you using JsonConvert together with JavascriptSerialzer? Aug 27, 2019 at 20:11
  • 2
    What Net framework are you using? Try using Net Core, the conversion to JSON is automatic.
    – Elvermg
    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; }
     }
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
  • 2
    Nicer solution with instantiation of the List property
    – Zephire
    Aug 27, 2019 at 20:40
  • Arghhhh! That was totally it! Thanks for the nested NewRootObject function. That worked nicely.
    – gwydion93
    Aug 28, 2019 at 2:25

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.