相关疑难解决方法(0)

如何在ASP.NET中将JSON反序列化为简单的Dictionary <string,string>?

我在JSON中有一个简单的键/值列表,通过POST发送回ASP.NET.例:

{ "key1": "value1", "key2": "value2"}
Run Code Online (Sandbox Code Playgroud)

我并没有想要进入强大的.NET对象

我只需要一个普通的旧的Dictionary(Of String,String),或者一些等价的(hash table,Dictionary(Of String,Object),old-school StringDictionary - hell,一个2-D字符串数组对我有用.

我可以使用ASP.NET 3.5中的任何可用内容,以及流行的Json.NET(我已经将其用于序列化客户端).

显然,这些JSON库都没有开箱即用的明显功能 - 它们完全专注于通过强大的合同进行基于反射的反序列化.

有任何想法吗?

限制:

  1. 我不想实现自己的JSON解析器
  2. 无法使用ASP.NET 4.0
  3. 宁愿远离旧的,已弃用的JSON ASP.NET类

json asp.net-ajax asp.net-3.5 json.net

642
推荐指数
12
解决办法
58万
查看次数

使用Web API返回匿名类型

使用MVC时,返回adhoc Json很容易.

return Json(new { Message = "Hello"});
Run Code Online (Sandbox Code Playgroud)

我正在使用新的Web API寻找此功能.

public HttpResponseMessage<object> Test()
{    
   return new HttpResponseMessage<object>(new { Message = "Hello" }, HttpStatusCode.OK);
}
Run Code Online (Sandbox Code Playgroud)

这会引发异常,因为DataContractJsonSerializer无法处理匿名类型.

我有这个替换此JsonNetFormatter基于Json.Net.如果我使用,这可行

 public object Test()
 {
    return new { Message = "Hello" };
 }
Run Code Online (Sandbox Code Playgroud)

但是我没有看到使用Web API的重点,如果我不回来HttpResponseMessage,我会更好地坚持使用vanilla MVC.如果我尝试使用:

public HttpResponseMessage<object> Test()
{
   return new HttpResponseMessage<object>(new { Message = "Hello" }, HttpStatusCode.OK);
}
Run Code Online (Sandbox Code Playgroud)

它将整个序列化HttpResponseMessage.

任何人都可以指导我一个解决方案,我可以在其中返回匿名类型HttpResponseMessage

c# json json.net asp.net-web-api

71
推荐指数
5
解决办法
6万
查看次数

我可以在.NET 4中序列化ExpandoObject吗?

我正在尝试使用,System.Dynamic.ExpandoObject所以我可以在运行时动态创建属性.稍后,我需要传递此对象的实例,并且使用的机制需要序列化.

当然,当我尝试序列化我的动态对象时,我得到了异常:

System.Runtime.Serialization.SerializationException未处理.

在Assembly'System.Core中输入'System.Dynamic.ExpandoObject',Version = 4.0.0.0,Culture = neutral,PublicKeyToken = b77a5c561934e089'未标记为可序列化.

我可以序列化ExpandoObject吗?是否有另一种方法来创建可序列化的动态对象?也许使用DynamicObject包装器?

我创建了一个非常简单的Windows窗体示例来复制错误:

using System;
using System.Windows.Forms;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Dynamic;

namespace DynamicTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {            
            dynamic dynamicContext = new ExpandoObject();
            dynamicContext.Greeting = "Hello";

            IFormatter formatter = new BinaryFormatter();
            Stream stream = new FileStream("MyFile.bin", FileMode.Create,
                                           FileAccess.Write, FileShare.None);
            formatter.Serialize(stream, dynamicContext);
            stream.Close();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

.net c# serialization dynamic expandoobject

27
推荐指数
3
解决办法
2万
查看次数