【发布时间】:2018-04-23 11:35:26
【问题描述】:
我想在 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);
}
}
}
【问题讨论】:
-
我们没有 JSON,我们没有您正在序列化/反序列化的类型,而且您还没有告诉我们它在哪一行失败......它将任何人都很难在这里做出猜测。 NRE 是一个非常常见的错误,@croxy 已经链接了一个很好的从哪里开始的演练
-
感谢@MarcGravell 的回复。我已经解决了这个问题。
标签: c# json linq-to-sql json.net json-serialization