Home > Mobile >  How to create new model and serialise json into it
How to create new model and serialise json into it

Time:12-13

Relatively new to C#, filling in for someone. There are a couple posts similar to this but I didn't quite understand them and didn't give clarity on the problem I'm having. I'm using Asp.net Core, C#, Razor pages.

I have a Json file, called "ResponseExample.json". I have a model called "ResponseModel" that is pretty much a replica of the data formatting / data set.

What I am trying to achieve is to put the JSON file data into my new model. Then I am assigning the model to session, so I can display the data on the view page. This is what I have so far so you can see what I am trying to achieve.

My problem currently is that I am not creating the model right so I cannot assign the json data to it. I'm not entirely sure the JSON deserialize is correct either.

public string LoadJson()
 {
     using (StreamReader r = new StreamReader("ResponseExample.json"))
     {
          string json = r.ReadToEnd();
          return json;
     }
}

public void SetSessionRatingResponseData(JObject response)
{
     new ResponseModel = JsonConvert.DeserializeObject<ResponseModel>(LoadJson());
     Set(SessionConstants.Response, ResonseModel);

}

CodePudding user response:

if you have a constructor defined on your ResponseModel,the new keyword is trying to initialize a new struct.

Try replacing the new call to create an instance of ResponseModel without the constructor and use the json Deserilize instead-- e.g.

ResponseModel responseModel = JsonConvert.DeserializeObject(LoadJson());

and set session constants accordingly

  •  Tags:  
  • c#
  • Related