2013-12-16 3 views
30

.net web api를 사용하여 json을 가져 와서 각도에 대해 프런트 엔드로 반환합니다. json은 객체 또는 배열 일 수 있습니다. 내 코드는 현재 객체가 아닌 배열에서만 작동합니다. tryparse하거나 내용이 객체인지 배열인지 판단 할 방법을 찾아야합니다.Json 결과가 객체인지 배열인지 확인합니다.

여기에 내 코드

public HttpResponseMessage Get(string id) 
    { 
     string singleFilePath = String.Format("{0}/../Data/phones/{1}.json", AssemblyDirectory, id); 
     List<Phone> phones = new List<Phone>(); 
     Phone phone = new Phone(); 
     JsonSerializer serailizer = new JsonSerializer(); 

     using (StreamReader json = File.OpenText(singleFilePath)) 
     { 
      using (JsonTextReader reader = new JsonTextReader(json)) 
      { 
       //if array do this 
       phones = serailizer.Deserialize<List<Phone>>(reader); 
       //if object do this 
       phone = serailizer.Deserialize<Phone>(reader); 
      } 
     } 

     HttpResponseMessage response = Request.CreateResponse<List<Phone>>(HttpStatusCode.OK, phones); 

     return response; 
    } 

이 일을 상기하지 않을 수 있습니다 가장 좋은 방법입니다. 그저 지금 내가있는 곳.

답변

71

Json.NET 사용하여, 당신이 할 수 있습니다 :

string content = File.ReadAllText(path); 
var token = JToken.Parse(content); 

if (token is JArray) 
{ 
    IEnumerable<Phone> phones = token.ToObject<List<Phone>>(); 
} 
else if (token is JObject) 
{ 
    Phone phone = token.ToObject<Phone>(); 
} 
+0

첫 번째 charcter를 확인할 수 있습니다. isArray = content [0] == '[' –

+0

@ johnny5 좋은 lib가 사용 가능할 때 수동으로 파싱하는 것은 일반적으로 좋은 생각이 아닙니다. 예를 들어, 공백을 확인하는 것을 잊었습니다. :) "[]"'은 유효한 json 배열입니다. – dcastro

+1

그 이유는 해킹이기 때문에 답변으로 게시하지 않았지만 가치있는 메모입니다. –

-3

당신은 항상 try/catch 블록 내부에 당신의 직렬화를 포장 할 수있다. try 블록 안에 배열로 역 직렬화하려고하면 객체 유형 인 경우 예외가 발생합니다.

try 
{ 
    //if array do this 
    phones = serailizer.Deserialize<List<Phone>>(reader); 
} 
catch //Deserialization of array failed - must be object 
{ 
    //if object do this 
    phone = serailizer.Deserialize<Phone>(reader); 
} 

나는 어떤 사람들은 이처럼 try/catch를 사용하여 싫은 줄 알지만, 효과적이라고 생각합니다.

+1

배열이 아닙니다. 'Deserialize'가 예외를 던질 유일한 이유가 아닙니다. 문자열은 단순히 잘못된 형식 일 수 있습니다. – dcastro

+0

네, 분명히 사실입니다. 그러나 OP는 어쨌든 예외 처리를 수행하지 않으므로이를 고려하지 않았습니다. –

+3

그리고 try/catch를 흐름 제어로 사용하는 것은 .NET에서 좋은 생각이 아닙니다. –

관련 문제