【问题标题】:Converting Json string to object with JavaScriptSerializer使用 JavaScriptSerializer 将 Json 字符串转换为对象
【发布时间】:2012-09-21 20:13:30
【问题描述】:

所以我将一个 Json 对象发送到我的服务器,并且我想将它转换为我称之为 PersonalPreferences 的强类型用户类型对象。

这里是 JS

{
"PersonalPreferences": [
    {
        "FavoriteFood": "Pasta with butter and cheese"
    },
    {
        "FavoriteSport": "Submission Wrestling"
    },
    {
        "FavoriteGame": "Starcraft 2"
    },
    {
        "FavoriteMusic": "Hip Hop"
    }
]
}

我创建了一个与我发送的 Json 对象匹配的类。

    [DataContract]
public class PersonalPreferences
{
    [DataMember]
    public string FavoriteFood { get; set; }

    [DataMember]
    public string FavoriteSport { get; set; }

    [DataMember]
    public string FavoriteGame { get; set; }

    [DataMember]
    public string FavoriteMusic { get; set; }

    public PersonalPreferences()
    {
    }

    public PersonalPreferences(string favoriteFood, string favoriteGame, string favoriteMusic, string favoriteSport)
    {
        this.FavoriteFood = favoriteFood;
        this.FavoriteGame = favoriteGame;
        this.FavoriteMusic = FavoriteMusic;
        this.FavoriteSport = favoriteSport;

    }
}

这是我的处理程序,它接收请求并将其转换为用户类型对象。 我的问题是 PersonalPreference 对象是空的。 jsSerializer.Deserialize 调用空构造函数,并且来自 Json 对象的值不会传递给 PersonalPreference 对象。 我检查了请求中的 Json 值是否作为字符串存在。

    [WebService(Namespace = "http://localhost:53243")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class JSonTestHandler : IHttpHandler, System.Web.SessionState.IReadOnlySessionState
{

    public void ProcessRequest(HttpContext context)
    {
        string jsonData = new StreamReader(context.Request.InputStream, System.Text.Encoding.UTF8).ReadToEnd();
        var jsSerializer = new JavaScriptSerializer();
        var personalPreferences = jsSerializer.Deserialize(jsonData, typeof(PersonalPreferences));
    }}

【问题讨论】:

    标签: asp.net json javascriptserializer


    【解决方案1】:

    提供的 json 格式字符串似乎有些问题。 如果检查以下 json 格式的字符串,它工作正常:

    {“FavoriteFood”:“黄油和奶酪意大利面”,“FavoriteSport”:“提交摔跤”,“FavoriteGame”:“星际争霸2”,“FavoriteMusic”: “嘻哈”}

    你是如何生成 Json 格式的字符串的?

    【讨论】:

    • 我从客户端 Javascript 中手动编写了 Json 格式。你有更好的办法吗?
    猜你喜欢
    • 2020-03-30
    • 1970-01-01
    • 2019-08-27
    • 2020-05-27
    • 1970-01-01
    • 1970-01-01
    • 2011-04-23
    • 2012-06-14
    • 2012-02-20
    相关资源
    最近更新 更多