在MVC中将JSON字符串转换为JsonResult [英] Convert JSON string to JsonResult in MVC

查看:502
本文介绍了在MVC中将JSON字符串转换为JsonResult的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在尝试提供模拟服务来提供JSON.我们将普通的JSON字符串存储在静态文件中,并希望将它们按原样提供给客户端,而无需任何其他包装. 例如.我们有json字符串{"result_code":200,{"name":"John", "lastName": "Doe"}},我们希望像这样的客户端获得json响应,而没有任何内容或数据包装器.

We are trying to make mock service to serve JSON. We have plain JSON strings stored in static files and want to serve them to client as they are, without any additional wrappers. E.g. we have json string {"result_code":200,{"name":"John", "lastName": "Doe"}} and we want to get json response on client just like this without any Content or Data wrappers.

我们有解决方案,其中我们使用数据协定并将json反序列化为C#对象,但这有点复杂,我们不需要它.

We have solution where we use data contracts and deserialize json to C# objects, but that's a bit complicated and we don't need it.

谢谢

推荐答案

您可以通过引用System.Web.Mvc来实现.我将快速控制台应用程序中的示例放在一起:

You can do this by referencing System.Web.Mvc. Example in a quick console app I threw together:

using System;
using System.Web.Mvc;
using Newtonsoft.Json;

namespace Sandbox
{
    class Program
    {
        private static void Main(string[] args)
        {
            //Added "person" to the JSON so it would deserialize
            var testData = "{\"result_code\":200, \"person\":{\"name\":\"John\", \"lastName\": \"Doe\"}}";

            var result = new JsonResult
            {
                Data = JsonConvert.DeserializeObject(testData)
            };

            Console.WriteLine(result.Data);
            Console.ReadKey();
        }

    }
}

您可以只从模拟方法返回JsonResult.

You can just return the JsonResult from the mock method.

这篇关于在MVC中将JSON字符串转换为JsonResult的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆