我正在创建一个Web服务来获取JSON中的输入。请参阅下面的代码:
注册.asmx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Serialization;
using System.IO;
using AnkTech.IsItFair.WebService.Providers;
using System.Json;
using System.Runtime.Serialization.Json;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json;
namespace WebService
{
/// <summary>
/// Summary description for Registration
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class Registration : System.Web.Services.WebService
{
[WebMethod]
public int SaveUser()
{
string json =
@"{""data"":[{""Id"":""518523721"",""Name"":""ftyft""}]}";
Users tempRecord = JsonConvert.DeserializeObject<Users>(json);
return 1;
}
}
}
用户.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Json;
using System.Runtime.Serialization.Json;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json;
namespace WebService.Providers
{
[JsonObject(MemberSerialization.OptIn)]
public class Users
{
[JsonProperty(PropertyName = "Id")]
public string Id { get; set; }
[JsonProperty(PropertyName = "Name")]
public string Name { get; set; }
}
}
当我检查我的对象 tempRecord 时,我发现了我的两个属性的空值,即 Id 和 Name。我做错了什么。请帮忙。
如果你是通过REST来做的,那么你可以这样做
[WebInvoke(Method = "GET", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "/index")]
反序列化 JSON
var userList = JsonConvert.DeserializeObject<List<User>>(json);
序列化 JSON
string json = JsonConvert.SerializeObject(employeeList, Formatting.Indented);
有关序列化和反序列化以及更多文档,您可以转到 Newtonsoft JSON 文档
您需要添加新的 poco 类,例如
public class UserData
{
[JsonProperty(PropertyName = "data")]
public IList<Users> Users { get; set; }
}
然后
var tempRecord = JsonConvert.DeserializeObject<UserData>(json);
它应该有效。