-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