2014-04-08 3 views
0

Xamarin.iOS/MonoTouch를 사용하여 iOS 응용 프로그램을 작성 중이며 약간의 딜레마가 있습니다. 우리는 우리의 로컬 sqlite 데이터베이스에 저장되는 모델로 처리되는 JSON 파일을 쿼리함으로써 애플리케이션과 함께 상당량의 데이터를 다운로드합니다. 문제는 필자가 작성한 클래스가 특정 유형에 대해 만들어 졌기 때문에 모든 JSON 데이터를 로컬 객체로 가져 오는 데 동일한 클래스를 사용할 수 있기를 원합니다. ,일반적인 사용법을위한 클래스 다시 쓰기 - C# MonoTouch

using System; 
using System.IO; 
using System.Net; 
using Newtonsoft.Json; 
using System.Collections.Generic; 

#pragma warning disable 0414 // Supressing Warning CS0414: 

namespace CommonLibrary { 
    public class JSONHandler { 

     // Debug Constants: 
     private static String DEBUG_FILE_TAG = "[JSONHandler] "; 

     // Define variables: 
     private Uri JSONRequestURL; 
     private bool RequestTimedOut; 
     private bool RequestSuccessful; 
     private string ResponseContent; 
     private List<Post> JSONObjects; 

     // Define objects: 
     private HttpWebRequest JSONWebRequest; 
     private HttpWebResponse JSONWebResponse; 


     // Constructor: 
     public JSONHandler(string requestURL){ 

      // Set request URL: 
      this.JSONRequestURL = new Uri(requestURL); 

      // Set default statuses: 
      this.RequestTimedOut = false; 
      this.RequestSuccessful = false; 

     } 


     // Create web request: 
     private void CreateWebRequest(){ 
      this.JSONWebRequest = (HttpWebRequest) WebRequest.Create (this.JSONRequestURL); 
      this.JSONWebRequest.Method = "GET"; 
      this.JSONWebRequest.Timeout = 5000; 
      this.JSONWebRequest.KeepAlive = false; 
      this.JSONWebRequest.AllowAutoRedirect = false; 
      this.JSONWebRequest.ContentType = "application/json"; 
     } 


     // Get request response: 
     private void GetRequestResponse(){ 
      try { 

       // Catch the response: 
       this.JSONWebResponse = (HttpWebResponse) this.JSONWebRequest.GetResponse(); 

       // Check the status code: 
       if (this.JSONWebResponse.StatusCode == HttpStatusCode.OK){ 

        // Get content: 
        StreamReader reader = new StreamReader (this.JSONWebResponse.GetResponseStream()); 
        this.ResponseContent = reader.ReadToEnd(); 

        // Close response: 
        this.JSONWebResponse.Close(); 

        // Check response length: 
        if (!String.IsNullOrWhiteSpace(this.ResponseContent)){ 
         this.JSONObjects = JsonConvert.DeserializeObject<List<Post>>(this.ResponseContent); 
         this.RequestSuccessful = true; 
        } else { 
         this.RequestSuccessful = false; 
        } 

       } else { 
        this.RequestSuccessful = false; 
       } 

      } catch (WebException){ 
       this.RequestTimedOut = true; 
       this.RequestSuccessful = false; 
      } catch (TimeoutException){ 
       this.RequestTimedOut = true; 
       this.RequestSuccessful = false; 
      } 
     } 


     // Fetch JSON from server: 
     public void FetchJSON(){ 
      this.CreateWebRequest(); 
      this.GetRequestResponse(); 
     } 


     // Return request status: 
     public bool RequestWasSuccessful(){ 
      return RequestSuccessful; 
     } 


     // Return timeout status: 
     public bool RequestDidTimeOut(){ 
      return RequestTimedOut; 
     } 


     // Get object count: 
     public int GetJSONCount(){ 
      return this.JSONObjects.Count; 
     } 


     // Get list of objects: 
     public List<Post> GetJSONObjects(){ 
      return this.JSONObjects; 
     } 


    } 
} 

당신이 볼 수 있듯이, 나는 다른 개체에 포스트에서 목록에 저장되어있는 유형을 변경하고, 예를 들어, 새로운 파일을 생성해야 JSONPost :

여기 내 코드입니다 JSONRunner, JSONLayer 등을 다루고 있으며, 하나의 클래스 인 JSONHandler만으로이를 처리하고 싶습니다. 희망을 갖고 여기 누군가가이 문제를 도와 줄 수 있기를 바랍니다. 이제 다음과 같은 수업을거야 :

  • 포스트
  • 레이어
  • RelayTeam
  • RelayRunner
  • RelayRunnerResult
  • MarathonRunner
  • MarathonRunnerResult

그리고 여러분 모두가 알 수 있듯이 이들 모두를 위해 중복 된 파일을 가지고있는 것은 좋지 않을 것입니다.

내가 얻을 수있는 도움에 대해 정말 감사드립니다.

안부, 조나단

+1

Generics를 찾고 계십니까? (http://msdn.microsoft.com/en-us/library/512aeb7t.aspx) – Mitch

+0

@Mitch 모름, 따라서 질문이지만, 나는 그것이라고 생각하지 않습니다. JSONHandler를 실행하는 위치에 따라 저장할 객체 유형을 지정할 수있는 일반 목록이 필요합니다. – Jonathan

답변

5

사용 제네릭 - JSONObjects 수집의 종류가 다양 유일한 경우, 당신은이

public class JSONHandler<T> { 
    ... 
    private List<T> JSONObjects; 

새 JSONHandler 인스턴스를 생성

, 당신이 할 수있는 유형을 지정할 수 있습니다

var handler = new JSONHandler<Post>(); 
var handler = new JSONHandler<Layer>(); 
var handler = new JSONHandler<RelayTeam>(); 
+0

이 문제를 해결하는 훌륭한 방법입니다. 나는 지금 휴가 중이지만 집에 돌아 가면 곧바로 시도 할 것이다. 큰 감사를 드린다! :) – Jonathan

+0

대단히 감사합니다. 이것은 완벽하게 작동했습니다! :) – Jonathan