在Web服务上使用JSON

时间:2013-08-29 08:45:09

标签: c# .net json web-services

我有一个从Web服务获取数据的Windows应用程序。

我需要使用JSON从Web服务发布或获取数据。

最好的方法是什么?在Web服务和Windows应用程序中?

请详细说明代码示例,因为我是JSON的新手。

3 个答案:

答案 0 :(得分:1)

使用Json.NET

您可以从NuGet下载并安装它。

要使用它,您需要创建一个与您的Json匹配的C#模型,然后调用:

string json = "";
MyObject obj = JsonConvert.DeserializeObject<MyObject>(json);

和序列化:

string json = JsonConvert.SerializeObject(new MyObject {});

有关更多示例和说明,请参阅documentation

答案 1 :(得分:0)

作为Json.Net的替代方案,您可以按照this文章中的说明使用WCF。 WCF是Microsoft提供的服务框架,是.Net的一部分。

答案 2 :(得分:0)

很难给出你的课程片段以及你想要实现的内容的例子。

但是,请查看您在webservice中可以使用的此功能

using Newsoft.Json;

public JsonResult FunctionName(string JsonString)
{
    if (JsonString!= null)
    {
        YourObject YourObjectInstance = new YourObject ();

        try
        {
            YourObjectInstance = JsonConvert.DeserializeObject<YourObject >(JsonString);
           //do something with the data                

           // return a Json response of either your object or another object type
           return Json(YourObjectInstance, JsonRequestBehavior.AllowGet);
        }
        catch
        {
            return new JsonResult();  //return empty JsonResult
        }
        }
        else
        {
            return new JsonResult();  //return empty JsonResult
        }

    }
}