如何以json格式返回数据返回字符串

时间:2016-05-25 10:32:43

标签: c# json winforms json.net

我有以下代码但它的返回数据是字符串类型..如何以json格式返回数据。

[HttpGet]
        public string Save(BookingInformation BookingJson)
        {
    SuccessResponse msg = new SuccessResponse();
    msg.FleetBookingId = objMaster.Current.Id.ToString();
    msg.Success = true;
    msg.Message = "Booking saved successfully";
    var obj = serializer.Serialize(msg).Trim('"');
    return obj;
}

通话方法

public async void getsave(BookingInformation BookingJson)
{
    var baseAddress = new Uri("http://mycar.com");

    string url = "/api/Jobs/SaveBooking";

    using (var httpClient = new HttpClient { BaseAddress = baseAddress })
    {
        var Jsonlines = JsonConvert.SerializeObject(BookingJson);
        //httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept-charset", "utf-8");

        //httpClient.DefaultRequestHeaders.TryAddWithoutValidation("authorization", "Basic *sample_token*");

        using (var content = new StringContent(Jsonlines, System.Text.Encoding.Default, "application/json"))
        {
            using (var response = await httpClient.PostAsync(url, content))
            {
                object responseData = await response.Content.ReadAsStringAsync();
            }
        }
    } 
}

结果是:如何只返回json。我想要以json格式返回数据

"{\"FleetBookingId\":\"36572\",\"Success\":true,\"Message\":\"Booking saved successfully\"}"

我想这样:

{"FleetBookingId":"36572","Success":true,"Message":"Booking saved successfully"}

3 个答案:

答案 0 :(得分:2)

不要从您的API方法返回一个字符串,而是SuccessResponse并让API的序列化程序完成其工作:

[HttpGet]
public SuccessResponse Save(BookingInformation BookingJson)
{
    SuccessResponse msg = new SuccessResponse();
    msg.FleetBookingId = objMaster.Current.Id.ToString();
    msg.Success = true;
    msg.Message = "Booking saved successfully";

    return msg;
}

答案 1 :(得分:0)

从控制器返回Json结果

    public ActionResult GetSuggestionFirst()
    {
        var search = Request.Params["term"].Trim();

        var itemList = (from items in db.TblProductSuggestionFirsts where items.Name.StartsWith(search) select new { label = items.Name, value = items.Name }).Take(50).ToList();

        return Json(itemList, JsonRequestBehavior.AllowGet);
    }

这个返回json对象(Json看起来像字符串,只是在Javascript中解析)

答案 2 :(得分:-1)

我得到了答案谢谢:)

var content = new JavaScriptSerializer().Serialize(msg);

JToken json = JObject.Parse(content);