从JSON结果C#中删除斜杠

时间:2017-11-02 06:33:34

标签: c# json

我正在以JSON格式显示一些数据,但是我的输出中有不需要的斜杠。这些是我的代码:

RestfulClient.cs

public class RestfulClient
{
    private static HttpClient client;
    private static string BASE_URL = "http://localhost:8080/";

    static RestfulClient()
    {
        client = new HttpClient();
        client.BaseAddress = new Uri(BASE_URL);
        client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));
    }

    public async Task<string> addition(int firstNumber, int secondNumber)
    {
        try
        {
            var endpoint = string.Format("addition/{0}/{1}", firstNumber, secondNumber);
            var response = await client.GetAsync(endpoint);
            return await response.Content.ReadAsStringAsync();
        }
        catch (Exception e)
        {
            HttpContext.Current.Server.Transfer("ErrorPage.html");
        }
        return null;
    }
}

AdditionController.cs

public class AdditionController : ApiController
{
    private RestfulClient restfulClient = new RestfulClient();
    public async Task<IHttpActionResult> Get(int firstNumber, int secondNumber)
    {
        var result = await restfulClient.addition(firstNumber, secondNumber);
        return Json(result);
    }
}

输出:

"{\"firstNumber\":9,\"secondNumber\":6,\"sum\":15}"

预期产出:

"{"firstNumber":9,"secondNumber":6,"sum":15}"

我是否必须反序列化字符串才能实现这一目标?如果是的话,我该怎么做呢?或者我是否必须更改application/json部分?有人请提前帮助我,谢谢你。

1 个答案:

答案 0 :(得分:1)

//尝试此代码需要转换特定类型

    public class Temp
    {
      public string firstNumber{ get;set;}
      public decimal secondNumber{ get;set;}
      public decimal sum{ get;set;}
    }


    public class AdditionController : ApiController
    {
     private RestfulClient restfulClient = new RestfulClient();
     public async Task<IHttpActionResult> Get(int firstNumber, int secondNumber)
     {
        var result = await restfulClient.addition(firstNumber, secondNumber);
        var resultDTO = JsonConvert.DeserializeObject<Temp>(result);
        return Json(resultDTO);
     }
    }