-4

我想从 C# 中 JSON 格式的 Country Master 表中获取 2 个不同的列值。在序列化它时,我收到一个错误“对象引用未设置为对象的实例”。这是我的代码如下:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace MDC_web.JSONs
{
    public partial class jsonCountry : System.Web.UI.Page
    {
        string countryname;
        int countryid;
        protected void Page_Load(object sender, EventArgs e)
        {
            countryname = Request.Form["CountryName"];
            countryid = Convert.ToInt32(Request.Form["CountryId"]);
            string jsonOutput = null;
            RegistrationDataClassesDataContext country = new 
            RegistrationDataClassesDataContext();
            var CountryID = (from coun in country.tbl_CountryMasters where 
            coun.CountryId == countryid select 
            coun.CountryId).SingleOrDefault();
            var CountryName = (from coun in country.tbl_CountryMasters where 
            coun.CountryName == countryname select 
            coun.CountryName).SingleOrDefault();
            //var CountryDetails = (from coun in country.tbl_CountryMasters 
            where coun.CountryId == countryid && coun.CountryName == 
            countryname select new {coun.CountryId, coun.CountryName 
            }).ToList() ;
            MemoryStream str = new MemoryStream();
            DataContractJsonSerializer serCountryId = new 
            DataContractJsonSerializer(CountryID.GetType());
            DataContractJsonSerializer serCountryName = new 
            DataContractJsonSerializer(CountryName.GetType());
            //DataContractJsonSerializer serCountryDetails = new 
            DataContractJsonSerializer(CountryDetails.GetType());
            //serCountryDetails.WriteObject(str, CountryDetails);
            serCountryId.WriteObject(str, serCountryId);
            serCountryName.WriteObject(str, serCountryName);
            str.Position = 0;
            StreamReader sr = new StreamReader(str);
            jsonOutput = sr.ReadToEnd();
            //jsonOutput = @"{""Success"":""True"", ""Country ID"":'"+serCountryId+"', ""Country Name"":'"+serCountryName+"'}";

            //jsonOutput = @"{""Success"" : ""True"", ""CountryID"" :  "' + CountryID + '"     +""','""+      ""Country Name"" : '" + CountryName + "'}"; 
            Response.Write(jsonOutput);
        }
      }
    }
4

1 回答 1

0

我认为您可以使用https://www.newtonsoft.com/json.It框架将为您完成所有工作您必须首先为您的 Json 对象创建一个模型并使用以下代码:

var data = JsonConvert.DeserializeObject<YourModel>(json);
于 2018-04-23T12:42:41.330 回答