C#web api戻りタイプをjsonに設定する2つの方法
7644 ワード
Web apiがapiインタフェースを書くときにデフォルトで返すのは、オブジェクトをシーケンス化してXML形式で返すことです.では、jsonに戻すにはどうすればいいのでしょうか.次の2つの方法を紹介します.
方法一:(改配置法)
Globalを見つけたasaxファイル、Application_Start()メソッドに次の文を追加します.
コードは次のとおりです.
方法一:(改配置法)
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); // api json GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear(); }
Globalを見つけたasaxファイル、Application_Start()メソッドに次の文を追加します.
コードは次のとおりです.
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
:
コードは のとおりです.
json , , String , 123, json "123";
( HttpResponseMessage)
public HttpResponseMessage PostUserName(User user)
{
String userName = user.userName;
HttpResponseMessage result = new HttpResponseMessage{ Content = new StringContent(userName,Encoding.GetEncoding("UTF-8"), "application/json") };
return result;
}
2:( ) 1では を したり、 り がStringタイプのjsonを したりして なので、web apiの シーケンス を わずに、 でシーケンス してから る
コードは のとおりです.
public HttpResponseMessage PostUser(User user)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
string str = serializer.Serialize(user); HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
return result;
}
2は がお めする で、インタフェースごとにそのいくつかのコードを り し かないために、1つの にカプセル して すると です.
public static HttpResponseMessage toJson(Object obj)
{
String str;
if (obj is String ||obj is Char)
{
str = obj.ToString();
}
else
{
JavaScriptSerializer serializer = new JavaScriptSerializer(); str = serializer.Serialize(obj);
}
HttpResponseMessage result = new HttpResponseMessage
{
Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json")
};
return result;
}
3:( も な ) 1は も ですが、 が きすぎて、すべての されるxmlフォーマットが されます.そうすれば、 3はapiインタフェースでxmlを すだけで、jsonに って に されるクラスを くことができます.
public class JsonContentNegotiator : IContentNegotiator { private readonly JsonMediaTypeFormatter _jsonFormatter;
public JsonContentNegotiator(JsonMediaTypeFormatter formatter) { _jsonFormatter = formatter; }
public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters) { var result = new ContentNegotiationResult(_jsonFormatter, new MediaTypeHeaderValue("application/json")); return result; } }
Appが つかりましたスタート のWebApiConfig.csファイルを き、Register(HttpConfiguration config)メソッドを つけて のコードを します.
コードは のとおりです.
var jsonFormatter = new JsonMediaTypeFormatter();
config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));
のコードは のとおりです.
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional } );
var jsonFormatter = new JsonMediaTypeFormatter();
config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter)
);
}
メソッド3 り がStringタイプである ,123のように りjsonは「123」となり, は じである. はweb apiは に ったオブジェクトをxmlとjsonの2つのフォーマットが する に えて、 の1つと の3つはxmlの しを して、 の2つはカスタムの しです.