【发布时间】:2016-09-05 06:28:38
【问题描述】:
在 MVC 应用程序中,我从给定服务器检索 json 字符串。 为了测试目的,我用 Chrome 检索了所有的拳头,我得到了这个
{
ultima_prelucrare: "2013-11-25",
ultima_declaratie: "2013-11-25",
tva_la_incasare: [ ],
tva: null,
telefon: "0745040840",
stare: "INREGISTRAT din data 04 Iulie 2007",
radiata: false,
numar_reg_com: "J40/12836/2007",
meta: {
updated_at: "2016-08-30T19:05:29.922418",
last_changed_at: null
},
judet: "Municipiul București",
impozit_profit: null,
impozit_micro: "2011-01-01",
fax: null,
denumire: "Infosystems4u S.R.L.",
cod_postal: "61954",
cif: "22052442",
adresa: "Aleea Baiut, 9a, Bucuresti",
act_autorizare: null,
accize: null
}
并且没问题。 现在回到我的应用程序。我已经有一个描述这种结构的模型。我有一个使用此字段在我的应用程序中添加客户的视图。 在我的场景中,我希望在为“cif”字段提供值之后,然后对给定的服务器发出 Web 请求并检索上面的 json 。 json 被检索,但是当我尝试使用 newtonsoft 反序列化时,它会引发关于“[”字符的异常。在这里,我注意到 [ 没有包含在引号字符之间,而是它来自服务器的方式。 我的代码很简短(现在代码只是在控制器的默认操作中,但我可以稍后解决这个问题):
//call openapi.ro
string CompanyCUI = "22052442";
// Create a new 'Uri' object with the specified Company ID string.
Uri myUri = new Uri("https://api.openapi.ro/api/companies/"+CompanyCUI+".json");
// Create a new request to the above mentioned URL.
WebRequest myWebRequest = WebRequest.Create(myUri);
//Add the required header to request
myWebRequest.Headers.Add("x-api-key", "8P4RP_kwn71Nt8VG7boFmQb_7NsihyQxT_x7JGcGQkvPdXZH2Q");
// Assign the response object of 'WebRequest' to a 'WebResponse' variable.
WebResponse myWebResponse = myWebRequest.GetResponse();
// Read the response into a stream
var dataStream = myWebResponse.GetResponseStream();
var reader = new StreamReader(dataStream);
var jsonResultString = reader.ReadToEnd();
// Deserialize
var CompanyInfoData = Newtonsoft.Json.JsonConvert.DeserializeObject<CustomerModels>(jsonResultString);
//Feed the model with retrieved data
//...
//Save all
//...
现在假设我发现 json 内容有什么问题,以及最终如何走得更远,下一步是在用户点击表单的“保存”按钮之前用检索到的值预先填充表单中的编辑框控件。困扰我的是我的表单中需要两个按钮,一个用于调用 Web 请求并填充所需的值,第二个是保存按钮,我真的不知道如何处理单个表单中的两个按钮。
提前感谢您的任何提示
【问题讨论】:
-
您的 json 无法通过 jsonlint.com 进行验证。您应该将您的字段放在双引号中,例如 "ultima_prelucrare": "2013-11-25", "ultima_declaratie": "2013-11-25",....
-
显示
CustomerModels的模型 -
现在就像: public class CustomerModels { // public string ultima_prelucrare { get;放; } 公共字符串 ultima_declaratie { 获取;放; } 公共列表 tva_la_incasare { 获取;放; } 公共字符串 tva { 获取;放; } 公共字符串电话 { 获取;放; } 公共字符串 accize { 得到;放; } }
-
您需要编辑问题(并显示它是什么,而不是什么有效!)显然不是
IEnumerable<T>
标签: c# asp.net json asp.net-mvc