2016-11-08 3 views
0

ANSWER는 LINQ to JSON을 사용하고 JObject를 사용하여 JSON을 실행 가능한 객체로 변환하는 방법을 설명합니다. 아래는 JSON에서 실행 가능한 객체로 나를 데려가 원래의 질문을 따르는 완성 된 코드입니다.VB.NET은 Newtonsoft JSON을 객체로 동적으로 비 직렬화합니다.

  'Parse string of JSON data into a JObject that can be accessed via VB.NET 
      Dim resultSet As JObject = JObject.Parse(responseBody) 

      'Data can be accessed as seen below 
      Dim cpu As String = CType(resultSet("KeyName"), String) 

=========================================== =================

나는 서비스 호출에 대한 여러 API 호출

{ 
    "resultSet": { 
    "_links": { 
     "self": "string", 
     "next": "string", 
     "previous": "string" 
    }, 
    "businessUnitId": 0, 
    "lastPollTime": "2016-11-08T21:45:46.510Z", 
    "totalRecords": 0, 
    "agents": [ 
     { 
     "agentId": 0, 
     "userName": "string", 
     "firstName": "string", 
     "middleName": "string", 
     "lastName": "string", 
     "emailAddress": "string", 
     "isActive": true, 
     "teamId": 0, 
     "teamName": "string", 
     "reportToId": 0, 
     "reportToName": "string", 
     "isSupervisor": true, 
     "lastLogin": "2016-11-08T21:45:46.510Z", 
     "lastUpdated": "2016-11-08T21:45:46.510Z", 
     "location": "string", 
     "custom1": "string", 
     "custom2": "string", 
     "custom3": "string", 
     "custom4": "string", 
     "custom5": "string", 
     "internalId": "string", 
     "profileId": 0, 
     "profileName": "string", 
     "timeZone": "string", 
     "country": "string", 
     "countryName": "string", 
     "state": "string", 
     "city": "string", 
     "chatRefusalTimeout": 0, 
     "phoneRefusalTimeout": 0, 
     "workItemRefusalTimeout": 0, 
     "defaultDialingPattern": 0, 
     "defaultDialingPatternName": "string", 
     "teamDefaultMaxChats": true, 
     "maxConcurrentChats": 0, 
     "notes": "string", 
     "createDate": "2016-11-08T21:45:46.510Z", 
     "inactiveDate": "2016-11-08T21:45:46.510Z", 
     "hireDate": "2016-11-08T21:45:46.510Z", 
     "terminationDate": "2016-11-08T21:45:46.510Z", 
     "rehireStatus": true, 
     "employmentType": 0, 
     "employmentTypeName": "Full-Time", 
     "referral": "string", 
     "atHome": true, 
     "hiringSource": "string", 
     "ntLoginName": "string", 
     "scheduleNotification": "5", 
     "federatedId": "string", 
     "sipUser": "string", 
     "useTeamMaxEmailInboxCount": true, 
     "maxEmailInboxCount": 0 
     } 
    ] 
    } 
} 

내가 Newto와 JSON 직렬화를 해제하고 : inContact은 (http://www.incontact.com/)

는 API 호출의 각이 방식으로 서식 JSON 가득 HTTP 응답을 받게 될 것입니다 nsoft. 나는 현재 HTTP 응답에 복용하고 실행 가능한 .NET 객체를 생성하는 JSON 직렬화를 해제하고

{ 
    "resultSet": { 
    "businessUnitId": 0, 
    "lastPollTime": "2016-11-08T21:45:46.604Z", 
    "teams": [ 
     { 
     "teamId": 0, 
     "teamName": "string", 
     "isActive": true, 
     "description": "string", 
     "notes": "string", 
     "lastUpdateTime": "2016-11-08T21:45:46.604Z", 
     "inViewEnabled": true, 
     "wfoEnabled": true, 
     "wfmEnabled": true, 
     "qmEnabled": true, 
     "maxConcurrentChats": 0, 
     "agentCount": 0, 
     "maxEmailInboxCount": true, 
     "inViewGamificationEnabled": true, 
     "inViewChatEnabled": true, 
     "inViewLMSEnabled": true, 
     "analyticsEnabled": true 
     } 
    ], 
    "agents": [ 
     { 
     "agentId": 0, 
     "firstName": "string", 
     "lastName": "string" 
     } 
    ] 
    } 
} 

그러나, 각기 다른 통화로 이와 같은 다른 키/값 쌍있을 것입니다. 요청이 성공적으로 가정, HTTP 요청을 생략, 그래서이 내 단축 코드를 수행합니다

문제는 내가 대신 문자열을 할 수있는의, 각각의 API 호출에 대한 특정 클래스가 필요하다는 것입니다
 If Not String.IsNullOrEmpty(responseBody) Then 
      ' Success. Do something with the response. 
      'Declare object for holding the JSON from the API call for this call only (class does not fit other calls) 
      Dim resultSet As GetAgentsAPICall = New GetAgentsAPICall 
      'Deserialize JSON response into the new resultSet object 
      resultSet = JsonConvert.DeserializeObject(responseBody) 

JSON 형식을 사용하여 키/값과 일치하는 속성을 가진 객체에 던져 넣습니다. 아래는 내가 그 (길이 이상 나열된 첫 번째) 바로 위의 API 호출에 소요 한 클래스입니다 :

Public Class GetAgentsAPICall 
    Public Property resultSet As Resultset 
End Class 

Public Class Resultset 
     Public Property _links As _Links 
     Public Property businessUnitId As Integer 
     Public Property lastPollTime As Date 
     Public Property totalRecords As Integer 
     Public Property agents() As Agent 
    End Class 

    Public Class _Links 
     Public Property self As String 
     Public Property _next As String 
     Public Property previous As String 
    End Class 

    Public Class Agent 
     Public Property agentId As Integer 
     Public Property userName As String 
     Public Property firstName As String 
     Public Property middleName As String 
     Public Property lastName As String 
     Public Property emailAddress As String 
     Public Property isActive As Boolean 
     Public Property teamId As Integer 
     Public Property teamName As String 
     Public Property reportToId As Integer 
     Public Property reportToName As String 
     Public Property isSupervisor As Boolean 
     Public Property lastLogin As Date 
     Public Property lastUpdated As Date 
     Public Property location As String 
     Public Property custom1 As String 
     Public Property custom2 As String 
     Public Property custom3 As String 
     Public Property custom4 As String 
     Public Property custom5 As String 
     Public Property internalId As String 
     Public Property profileId As Integer 
     Public Property profileName As String 
     Public Property timeZone As String 
     Public Property country As String 
     Public Property countryName As String 
     Public Property state As String 
     Public Property city As String 
     Public Property chatRefusalTimeout As Integer 
     Public Property phoneRefusalTimeout As Integer 
     Public Property workItemRefusalTimeout As Integer 
     Public Property defaultDialingPattern As Integer 
     Public Property defaultDialingPatternName As String 
     Public Property teamDefaultMaxChats As Boolean 
     Public Property maxConcurrentChats As Integer 
     Public Property notes As String 
     Public Property createDate As Date 
     Public Property inactiveDate As Date 
     Public Property hireDate As Date 
     Public Property terminationDate As Date 
     Public Property rehireStatus As Boolean 
     Public Property employmentType As Integer 
     Public Property employmentTypeName As String 
     Public Property referral As String 
     Public Property atHome As Boolean 
     Public Property hiringSource As String 
     Public Property ntLoginName As String 
     Public Property scheduleNotification As String 
     Public Property federatedId As String 
     Public Property sipUser As String 
     Public Property useTeamMaxEmailInboxCount As Boolean 
     Public Property maxEmailInboxCount As Integer 
End Class 

내가 20 또는 30과 유사한 긴 클래스 사전 구축을 피하기 위해 노력하고있어, 그리고 대신 구축 수정 가능한 목록이나 개체를 즉시 업로드 할 수 있습니다. 값을 가져 와서 데이터베이스에 저장하거나 수정 한 다음 다른 API 호출을 사용하여 값을 POST로 되돌려 야합니다. 누구나 모범 사례가 있습니까, 아니면 20-30 개의 거대한 클래스 정의가 붙어 있습니까?

시간 내 주셔서 감사합니다. 또한 LINQ를 사용하여 조회 할 수있는 JObject

답변

1

구문 분석은, (참조 Newtonsoft.Json.Linq 네임 스페이스 아래 앉아 Newtonsoft의 LINQ to JSON API) :

JObject o = JObject.Parse(@"{ 
    'CPU': 'Intel', 
    'Drives': [ 
     'DVD read/writer', 
     '500 gigabyte hard drive' 
    ] 
}"); 

string cpu = (string)o["CPU"]; 
// Intel 

string firstDrive = (string)o["Drives"][0]; 
// DVD read/writer 

IList<string> allDrives = o["Drives"].Select(t => (string)t).ToList(); 
// DVD read/writer 
// 500 gigabyte hard drive 

예는 C#으로,하지만 당신은 관련 VB를 찾을 수 있습니다. NET에서 StackOverflow에 대한 답변 (예 : the answer here보기).

+0

정확히 내가 필요로하는 것은 액세스하고 조작 할 수있는 일반화 된 개체로 구문 분석하는 메서드입니다. 고맙습니다 trashr0x –

+0

다행입니다. – trashr0x

관련 문제