我正在创建一个需要返回 JSON 格式的 API/Web 服务。我还需要将 Web 服务创建为 POST 请求 下面的示例代码,请在本文末尾查看更多源代码片段。
Meta meta = new Meta();
meta.recipes = new List<Recipe>();
JavaScriptSerializer js = new JavaScriptSerializer();
string strJSON = js.Serialize(meta);
return strJSON;
问题:当我在几个 REST 控制台(尝试过的控制台列表)和 ASP.NET 客户端中尝试响应时,我得到的这种格式在每个“之前都有一个额外的“d”和额外的 \。请参见下面的返回输出:
{"d":"{\"count\":\"0\",\"status\":\"500\",\"recipes\":[]}"}
当我尝试删除序列化时,我得到以下格式:
<Meta xmlns:xsi="w3.org/2001/XMLSchema-instance"; xmlns:xsd="w3.org/2001/XMLSchema"; xmlns="tempuri.org/">; <count>1</count> <status>200</status> <recipes> <Recipe> <recipeID>1</recipeID> <recipeName>Apple Pie</recipeName> <imageURL>service/it.jpg</imageURL> <rating/> </Recipe> </recipes> </Meta>
但我希望它采用以下格式:
{"count":"0","status":"500","recipes":[]}
[WebMethod(Description = "Return all Recipe...")]
[ScriptMethod( ResponseFormat = ResponseFormat.Json)]
public Meta RecipeList(string ingredientId, string cuisineId, string dishTypeId, string courseId)
即使我返回元对象并且不添加序列化,这仍然返回 XML
问题:
- 我认为正确的 JSON 格式应该没有这个“d”和 . 这是真的还是输出的正确 JSON 格式实际上带有“d”和 \?
- 如果应该没有,那么您建议在服务器端还是客户端进行更正?
- 我应该如何在服务器端纠正这个问题?
如何在客户端纠正这种情况?
[WebMethod(Description = "Return all Recipe...")] [ScriptMethod( ResponseFormat = ResponseFormat.Json)] public string RecipeList(string ingredientId, string cuisineId, string dishTypeId, string courseId, string occasionId, string considerationId, string recipeType, string readyTime, string favouritebyUserId, string bookmarkbyUserId) { DataSet ds = new DataSet(); int rTime = 0; if (readyTime == "") rTime = 0; else rTime = Convert.ToInt32(readyTime); ds = RecipeBLL.SearchRecipe(ingredientId, cuisineId, dishTypeId, courseId, occasionId, considerationId, recipeType, rTime); // Create a multidimensional jagged array string[][] JaggedArray = new string[ds.Tables[0].Rows.Count][]; int i = 0; Meta meta = new Meta(); int count = 0; meta.recipes = new List<Recipe>(); foreach (DataRow rs in ds.Tables[0].Rows) { Recipe recipe = new Recipe { recipeID = rs["RecipeId"].ToString(), recipeName = rs["RecipeTitle"].ToString(), imageURL = rs["Photo"].ToString(), rating = rs["Rating"].ToString() }; meta.recipes.Add(recipe); //mlist.Add(recipe); count++; } if (count != 0) meta.status = "200"; else meta.status = "500"; meta.count = count.ToString(); JavaScriptSerializer js = new JavaScriptSerializer(); string strJSON1 = js.Serialize(meta); return strJSON1; }