2012-07-13 2 views
0

이는 "응용 프로그램"의 여러 개체를 포함 내 JSON 파일입니다WCF REST에서 JSON 배열을 구문 분석 할 수 없습니다

{"Application":[{"appid":"0","appname":"application0"}, 
       {"appid":"1","appname":"application1"}, 
       .... 
       ]} 
내 WCF REST 서비스 방식에 안드로이드 코드에서 발생하고 있습니다

:

public string AcceptApplication(Stream inputStream) 
{ 
    StreamReader r = new StreamReader(inputStream); 
    string jsonstring = r.ReadToEnd(); 
    try 
    { 
     List<ApplicationEntity> list = JsonConvert.DeserializeObject<List<ApplicationEntity>>(jsonstring); 
     for (int i = 0; i < list.Count; i++) 
     { 
     // using data 
     } 
    } 
    catch (Exception E) 
    { 
     Logger.Error(E.Message); 
    } 

내 ApplicationEntity :

[WebInvoke(Method = "POST", UriTemplate = "/AcceptApp", RequestFormat = WebMessageFormat.Json, 
    ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.WrappedRequest)] 
[OperationContract] 
string AcceptApplication(Stream jsonstring); 

그리고 여기 메소드 정의의

public class ApplicationEntity 
{ 
    public string appid { get; set; } 
    public string appname { get; set; } 
} 

나는 jsonstring 받고 있어요,하지만 오류가 나는군요 :

Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (e.g.  
{"name":"value"}) into type 
'System.Collections.Generic.List`1[ApplicationEntity]' because the 
type requires a JSON array (e.g. [1,2,3]) to deserialize correctly. 
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so 
that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array 
or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type 
to force it to deserialize from a JSON object. 

답변

2

당신이 구문 분석하려고하는 JSON 문자열 목록 또는 배열이 아닌. "Application"이라는 속성이있는 배열입니다. 이 시도 :

public class ApplicationObject 
{ 
    public List<ApplicationEntity> Application { get; set; } 
} 
... 
var apps = JsonConvert.DeserializeObject<ApplicationObject>(jsonstring); 

지금 당신이 apps.Application에있는 목록에 액세스 할 수 있습니다.

+0

오류가 발생했습니다. 개체 참조가 개체의 인스턴스로 설정되지 않았습니다. foreach (apps.Applications의 var 항목) { 시도 { ApplicationEntity ent = new ApplicationEntity(); ent = item; 상태 = InsertInstalledApps (ent); } catch (예외 ex) { Logger.Error (ex); } } – benjamin54

+0

ApplicationEntity 인스턴스를 만들 필요는 없으며 foreach 항목의 "항목"은 ApplicationEntity 인스턴스입니다. 따라서 Status = InsertInstalledApps (item)를 호출하면됩니다. 그 방법 안에서 예외가 발생하지 않았습니까? – Leo

+0

동일한 줄에 오류가 없습니다. var apps = JsonConvert.DeserializeObject (jsonstring); 나는 심지어 추가했다 : ApplicationObject apps = new ApplicationObject(); 그 줄 앞에. 그러나 운이 없다. – benjamin54

관련 문제