JsonDeserialize возвращает нулевые значения после попытки привязки к модели - PullRequest
0 голосов
/ 30 октября 2018

Я пытаюсь связать значения из sample.json с моделью PayInfo []. Я использую Newtonsoft JsonDeserialize и хотя это

а) определение правильного пути (sample.json) и

б) правильный доступ к моим моделям,

это не связывает каждое значение данных sample.json с моделью. При отладке в полях отображаются нулевые значения, хотя в файле sample.json содержится много фиктивных данных. Обратите внимание, что моя цель - десериализовать данные из sample.json, привязать их к модели и отобразить в моем представлении.

Любые советы будут высоко оценены !!

JsonSerializeMethod

 public static List<PayInfo> ReadJson()
{
    // read file into a string and deserialize JSON to a type
    var payInfoData1 = JsonConvert.DeserializeObject<List<PayInfo>>(File.ReadAllText(@"JsonData\sample.json"));
    // deserialize JSON directly from a file
    using (StreamReader file = File.OpenText(@"JsonData\sample.json"))
    {
        JsonSerializer serializer = new JsonSerializer();
        // PayInfo[] payInfoData = (PayInfo[])serializer.Deserialize(file, typeof(PayInfo[]));
        payInfoData1 = (List<PayInfo>)serializer.Deserialize(file, typeof(List<PayInfo>));
        return payInfoData1;
    }
}

Модель

public class PayInfo
{

    public Payee Payee { get; set; }
    public Payment Payment { get; set; }
    public List<Remittance> Remittance { get; set; }

}
public class Payee
{
    [JsonProperty("Name")]
    public string PayeeName { get; set; }

    [JsonProperty("Fax")]
    public string PayeeFax { get; set; }

    [JsonProperty("Phone")]
    public string PayeePhone { get; set; }

    public Address Address { get; set; }

    public string Attention { get; set; }
    public string SubmissionDate { get; set; }
    public string PaymentExp { get; set; }
}


public class Payment
{
    public string PAN { get; set; }
    public string CVV { get; set; }
    public string Exp { get; set; }


}
public class Address
{

    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string City { get; set; }
    public string StateOrProvince { get; set; }
    public string Zip { get; set; }

}
public class Remittance
{
    public string PayorName { get; set; }
    public string PayorId { get; set; }
    public string InvoiceNo { get; set; }
    public string Description { get; set; }
    public string Amount { get; set; }
}

* Вот мой контроллер

    public class HomeController : Controller
{
    // GET: /Home/
    [HttpGet]
    [Route("")]
    public IActionResult Index()
    {
        // PayInfo[] payData = JsonToFile<PayInfo[]>.ReadJson();
        // return View(payData);
        PayInfo payList = new PayInfo();
        var wordUp = JsonToFile<payList>.ReadJson();
        return View(payList);
    }
}

JsonData из sample.json

   [
  {
    "Payee": {
      "Name": "BLEENDOT",
      "Fax": "(942) 424-2678",
      "Phone": "(980) 494-2960",
      "Address": {
        "Address1": "551 Hoyt Street",
        "Address2": "",
        "City": "Rivera",
        "StateOrProvince": "Ohio",
        "Country": "US",
        "PostalCode": 40529
      },
      "Attention": "Mcdaniel Blankenship",
      "SubmissionDate": "2017-02-06"
    },
    "Payment": {
      "PAN": 1313027774141142,
      "CVV": 723,
      "Exp": "11/2017"
    },
    "Remittance": [
      {
        "PayorName": "Cubix",
        "PayorId": 8314,
        "InvoiceNo": 16981,
        "Description": "Aliquip et aliqua nisi sit sit sint voluptate exercitation quis dolore aute tempor mollit fugiat.",
        "Amount": "$28,192.35"
      },
      {
        "PayorName": "Oceanica",
        "PayorId": 6013,
        "InvoiceNo": 930,
        "Description": "Cillum est est aute aliquip magna occaecat eiusmod labore velit consequat aute occaecat non eu.",
        "Amount": "$76,664.75"
      },
      {
        "PayorName": "Biotica",
        "PayorId": 18461,
        "InvoiceNo": 542,
        "Description": "Exercitation minim ex sint velit amet.",
        "Amount": "$30,718.78"
      }
    ]
  }
]

1 Ответ

0 голосов
/ 01 ноября 2018

Во-первых, имена ваших свойств не верны с именами json; они должны быть одинаковыми, или вы должны использовать атрибут jsonProperty . И имя основного класса не правильно; Ваш основной класс должен быть классом, который включает в себя ваш подкласс, такой как «Получатель платежа», «Адрес» и остальные, посмотрите мои коды, я немного исправил.

    public class PayInfo
    {

        public Payee Payee { get; set; }
        public Payment Payment { get; set; }
        public List<Remittance> Remittance { get; set; }

    }
    public class Payee
    {
        [JsonProperty("Name")]
        public string PayeeName { get; set; }

        [JsonProperty("Fax")]
        public string PayeeFax { get; set; }

        [JsonProperty("Phone")]
        public string PayeePhone { get; set; }

        public Address Address { get; set; }

        public string Attention { get; set; }
        public string SubmissionDate { get; set; }
        public string PaymentExp { get; set; }
    }


    public class Payment
    {
        public string PAN { get; set; }
        public string CVV { get; set; }
        public string Exp { get; set; }


    }
    public class Address
    {

        public string Address1 { get; set; }
        public string Address2 { get; set; }
        public string City { get; set; }
        public string StateOrProvince { get; set; }
        public string Zip { get; set; }

    }
    public class Remittance
    {
        public string PayorName { get; set; }
        public string PayorId { get; set; }
        public string InvoiceNo { get; set; }
        public string Description { get; set; }
        public string Amount { get; set; }
    }

И вы можете изменить свой метод следующим образом: использовать список вместо массива будет проще.

     public static List<PayInfo> ReadJson()
    {
        // read file into a string and deserialize JSON to a type
        var payInfoData1 = JsonConvert.DeserializeObject<List<PayInfo>>(File.ReadAllText(@"JsonData\sample.json"));
        // deserialize JSON directly from a file
        using (StreamReader file = File.OpenText(@"JsonData\sample.json"))
        {
            JsonSerializer serializer = new JsonSerializer();
            // PayInfo[] payInfoData = (PayInfo[])serializer.Deserialize(file, typeof(PayInfo[]));
            payInfoData1 = (List<PayInfo>)serializer.Deserialize(file, typeof(List<PayInfo>));
            return payInfoData1;
        }
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...