我希望在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);
}
}
}
答案 0 :(得分:0)
我认为您可以使用https://www.newtonsoft.com/json.It框架为您完成所有工作 您必须首先使用以下代码创建Json对象的模型:
var data = JsonConvert.DeserializeObject<YourModel>(json);