如何使Web API正确地将JSON.NET序列化的字符串对象发送回客户端



我使用jsonconvert.serialializeObject()序列化ienumerbale对象;它产生带有引号的字符串和带空格的逃生角色

来自Web API控制器我使用下面的代码返回该字符串

[HttpGet]
public string GetDegreeCodes(int id)
{
    string result = //output from JsonConvert.SerializeObject( );
    return result;
}

" [{{" Legerid ":1," degreeName ":"高中"," imagesrc ":":" http://bootsnipp.com/apple-touch-icon-114x114-pre "," description ":":" 上高中 度 r '},{" LegerId ":2," degreeName ":" Asseciate "," imagesrc ":":" http://bootsnipp.com/apple-touch-icon-114x114-pre "," description ":":" 获得合伙人 度 r '},{" Legerid ":3," degreeName ":" bachelor "," imagesrc ":':':" http://bootsnipp.com/apple-touch-icon-114x114-pre "," description ":":" 获得单身汉 度 r '},{" LegerId ":4," degreeName ":" masters "," imagesrc ":":" http://bootsnipp.com/apple-touch-icon-114x114-pre "," description ":":" 获得主人 度量 r '},{" legureid ":5," degreeName ":" doctrate "," imagesrc ":':" http://bootsnipp.com/apple-touch-icon-114x114-pre "," description ":":" 获得博士学位"}]"

这是我的ajax,由于额外的包装和逃脱字符,它无法正确识别JSON,

$.ajax({
        url: "/api/helloservice/getdegreecodes",
        type: "get",
        contentType: "application/text",
        data: { id: 1 }
    }).done(function (data) {
        if (data.length > 0) {
            for (i = 0; i < data.length; i++) {
                viewEduModel.degreeCodes.push(data[i]);
            }
        }
    });

我需要使用jsonconvert.serializeobject,因为我将其作为json缓存 在我的redis缓存服务器中使用Booksleeve,我不需要 每次重新序列化并从数据库中阅读。我如何避免发送Web API控制器发送 报价和反斜线?我可以简单地返回iEnumerable和 让Web API进行JSON序列化,但我需要在Redis上缓存 侧面

您可以类似以下内容:

[HttpGet]
public HttpResponseMessage GetDegreeCodes(int id)
{
    StringContent sc = new StringContent("Your JSON content from Redis here");
    sc.Headers.ContentType = new MediaTypeHeaderValue("application/json");
    HttpResponseMessage resp = new HttpResponseMessage();
    resp.Content = sc;
    return resp;
}

通过使用此功能,您可以通过代码调用WebAPI。

using (var client = new WebClient()) //WebClient  
{
   string mystring = "";               
  client.Headers.Add("Content-Type:application/json"); //Content-Type  
  client.Headers.Add("Accept:application/json");                      
  var dataa = Encoding.UTF8.GetBytes("{"Username":"sdfsd"}");                      
  byte[] a = client.UploadData("your API url", "POST",dataa);                        
  myString = Encoding.UTF8.GetString(a);
  
  }

相关内容

  • 没有找到相关文章

最新更新