swagger如何返回map字段註釋

1.效果圖如下:

2.controller層代碼:

 
import java.util.HashMap;
import java.util.Map; 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController; 
import com.mengyoou.core.serialize.ResponseMsg; 
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses; 
 
@Api(value="返回字段添加註釋信息controller",tags={"返回字段添加註釋信息controller"})
@RestController
public class TestController { 
	@ApiOperation(value="返回字段添加註釋信息", notes="返回字段添加註釋信息")
    @RequestMapping(value={"demo"}, method={RequestMethod.GET})
    @ApiResponses({
    	@ApiResponse(code = 200, message = "ok", response=User.class),
    })
    public ResponseMsg demo() {
    	User user = new User();
    	Map<String, Object> map = new HashMap<>();
    	map.put("user", user);
    	return new ResponseMsg(map);
    } 
}

3.用戶實體的代碼:

  
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;  
@ApiModel(value="登錄成功後返回的個人信息")
@Data
public class User {
	
	    @ApiModelProperty(value="用戶名")
	    private String userName;//用戶名
	    @ApiModelProperty(value="密碼")
	    private String password;//用戶名 
}

4.關鍵點:

接口 Swagger 顯示返回模型的註釋

mark:環境看之前文章

目的:web api controller 調用 asp.net mvc controller,讓swagger裡面的返回模型支持註釋

關鍵:對返回消息類的封裝,返回數據為泛型,swagger就能顯示model的註釋瞭

JsonMsg

/// <summary>
/// 返回消息
/// </summary>
public class JsonMsg<T> where T : class
{
    /// <summary>
    /// 狀態碼
    /// </summary>
    public int code { get; set; }
    /// <summary>
    /// 消息
    /// </summary>
    public string msg { get; set; }
    /// <summary>
    /// 內容
    /// </summary>
    public T obj { get; set; }
    /// <summary>
    /// 圖標
    /// </summary>
    public int icon { get; set; }
    public static JsonMsg<T> OK(T obj, string msg = "成功") 
    {
        return new JsonMsg<T>() { code = 1, msg = msg, obj = obj, icon = 1 };
    }
    public static JsonMsg<T> Error(T obj, string msg = "失敗")
    {
        return new JsonMsg<T>() { code = 0, msg = msg, obj = obj, icon = 1 };
    }
}

OrderDto

public class OrderDto
{
    public string Name { get; set; }
}

HomeController

public JsonResult GetOrderInfo()
{
    var order = new OrderDto { Name = "203022200" };
    return Json(order);
}

HomeAPIController

[AllowAnonymous]
public JsonMsg<OrderDto> testResultDataDesc3()
{
    HomeController controller = GetController<HomeController>();
    var d = (OrderDto)controller.GetOrderInfo().Data;
    return JsonMsg<OrderDto>.OK(d);
}

效果

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: