xyz
xyz

Reputation: 549

Deserializing the JSON in C#

I am having the JSON object which is stored in to in to the Variable. The JSON looks like

{
 "data":
[
{"SNumber":"05",
 "LName":"TyJ",
 "LNameMarkup":"18/TyJ"
}]}

I created the Model class for the JSON like

namespace SetName.Models
{
public class SNameDTO
{     
 public class Datum
 {
  public string SNumber { get; set; }
  public string LName { get; set; }
  public string LNameMarkup { get; set; }
 }

 public class RootObject
 {
  public List<Datum> data { get; set; }
 }
 }
 }

Now I want to deserialize this JSON I can get the LName from it

  var retSName = GetSName(StockNumber);   //stores the JSON shown above

I replaced the above code with

  SNameDTO.RootObject retSName = GetSName(StockNumber);

It throws error like

Cannot implicitly convert type 'string' to 'SetName.Models.SNameDTO.RootObject'

I am trying to use the Model Class instead of the dynamic objects.

Upvotes: 0

Views: 183

Answers (2)

Viju
Viju

Reputation: 95

Used Newtonsoft JSON nuget package, able to Deserialize it as below, Hope this helps.

class Program
{
    static void Main(string[] args)
    {
        var json = "{\"SNumber\":\"05\",\"LName\":\"TyJ\",\"LNameMarkup\":\"18/TyJ\"}";

        var jsonCollection =
            "[{\"SNumber\":\"05\",\"LName\":\"TyJ\",\"LNameMarkup\":\"18/TyJ\"},\r\n{\"SNumber\":\"10\",\"LName\":\"TyJ2\",\"LNameMarkup\":\"20/TyJ\"}]";

        var jsonRootObject = "{ \"data\" : [{\"SNumber\":\"05\",\"LName\":\"TyJ\",\"LNameMarkup\":\"18/TyJ\"}, {\"SNumber\":\"10\",\"LName\":\"TyJ2\",\"LNameMarkup\":\"20/TyJ\"}]}";

        var data = JsonConvert.DeserializeObject<SNameDTO.Datum>(json);
        var dataCollection = JsonConvert.DeserializeObject<List<SNameDTO.Datum>>(jsonCollection);
        var rootObject = JsonConvert.DeserializeObject<SNameDTO.RootObject>(jsonRootObject);
    }
}


public class SNameDTO
{
    public class Datum
    {
        public string SNumber { get; set; }
        public string LName { get; set; }
        public string LNameMarkup { get; set; }
    }

    public class RootObject
    {
        public List<Datum> data { get; set; }
    }
}

Upvotes: 0

oerkelens
oerkelens

Reputation: 5161

To actually deserialize your JSON string, you need to do a bit more. If you use Json.Net (available on NuGet) you can try something like:

var myClass = JsonConvert.DeserializeObject<RootObject>(GetSName(StockNumber));

Upvotes: 1

Related Questions