在 vb .net 或 c#.net 中将对象转换为 json

convert object to json in vb .net or c#.net

我正在使用 vb.net web api 开发 restful web 服务 api 2,我正在尝试从主体传递参数以执行我的存储过程,

{
    "id": "2016", 
    "Type":"1", 
    "Year": "1"
}

这是我从主体传递的数据,这是错误

{ "message": "System.InvalidCastException: Conversion from type 'JObject' to type 'String' is not valid.\r\n at Microsoft.VisualBasic.CompilerServices.Conversions.ToString(Object Value)\r\n at WebApplication7.Controllers.SubjectsController.getSubjects(Object data) in C:\Users\Junaida\documents\visual studio 2015\Projects\WebApplication7\WebApplication7\Controllers\SubjectsController.vb:line 30" }

我的vb代码:

    <HttpPost>
    Function getSubjects(<FromBody> ByVal data As Object) As IHttpActionResult
        Try
            Using entities As IAPD_DBEntities = New IAPD_DBEntities()

                Dim year, type, id As String
                Dim dictionary = JsonConvert.DeserializeObject(data) 'As  Dictionary(Of String, String)


                Dim startno As Integer = 0
                If year = 1 Then
                    startno = 0
                ElseIf year = 2 And type = 1 Then
                    startno = 366
                ElseIf year = 2 And type = 3 Then
                    startno = 52
                ElseIf year = 2 And type = 2 Then
                    startno = 13
                End If

                dictionary.Add("id", id)
                dictionary.Add("Type", type)
                dictionary.Add("Year", year)

                Return Ok(entities.SP_Messages_GetinfoArchive_ByID(startno, id, type, year).ToList)
            End Using
        Catch e As Exception
            Return BadRequest(e.ToString)
        End Try
    End Function
End Class

我认为您的 data 对象已经是 JObject 并且 JsonConvert.DeserializeObject 需要一个字符串。您应该能够在不反序列化它的情况下访问它的属性,如下所示:

dictionary.add("id", data("id").ToString())
dictionary.add("Type", data("Type").ToString())
dictionary.add("Year", data("Year").ToString())

应该可以。

您需要创建一个 class,其属性与传入的 JSON 结构的字段相匹配,然后 MVC Web API 将为您进行解析!无需反序列化自己。

示例class:

Public Class SubjectParams
    Public Property id As String
    Public Property type As String
    Public Property year As String
End Class

然后像这样使用它:

<HttpPost>
Function getSubjects(<FromBody> ByVal data As SubjectParams) As IHttpActionResult

然后您可以使用data.iddata.type

如果您需要其他类型的属性,只需这样做即可(特别是 Integer 似乎至少对某些属性有意义)。