2014-11-13 4 views
2

내가 QByteArray가에서 구문 분석,QT5 JSON은 QByteArray

{"response": 
     {"count":2, 
     "items":[ 
      {"name":"somename","key":1"}, 
      {"name":"somename","key":1"} 
]}} 

구문 분석하고 필요한 데이터를 얻기 위해 필요한이 JSON을 포함 , 두 번째 디버그 아무것도 표시되지 않습니다.

그렇지 않으면 구문 분석해야합니까, 아니면이 방법이 작동하지 않는 이유는 무엇입니까?

+0

audioDoc을 어디에 선언합니까? – TheDarkKnight

+0

@ Merlin069 죄송합니다. 사이트의 오타가 –

답변

1

특히 qt API에 익숙하지 않지만 일반적으로 JSON 배열 (예 : "항목"값)이 아니면 JSON 개체를 배열로 강제 변환 할 수 없습니다. 당신이 중 하나의 형식을 알고, 또는 유형에 대한 객체를 요청하여 해결해야 할

QJsonObject itemObject = audioDoc.object(); 
QJsonObject responseObject = itemObject["response"].toObject(); 
QJsonArray itemArray = responseObject["items"].toArray(); 
+0

으로 수정되었습니다. 고맙습니다. 하지만 결국'QJsonObject responseObject = itemObject [ "response"]'method'toObject()'에 추가되어야합니다. –

2

:

은 아마 당신은 뭔가를 원한다. QJsonValue는 등 끝나면 IsArray, toArray, isBool, toBool, 같은 기능을 가지고 이유입니다

당신이 형식을 알고 있다면, 당신은 이런 식으로 뭔가를 할 수 있습니다 : -

// get the root object 
QJsonDocument itemDoc = QJsonDocument::fromJson(answer); 
QJsonObject rootObject = itemDoc.object(); 

// get the response object 
QJsonValue response = rootObject.value("response"); 
QJsonObject responseObj = response.toObject(); 

// print out the list of keys ("count") 
QStringList keys = responseObj.keys(); 
foreach(QString key, keys) 
{ 
    qDebug() << key; 
} 

// print the value of the key "count") 
qDebug() << responseObj.value("count"); 

// get the array of items 
QJsonObject itemArrayObj = responseObj.value("items"); 

// check we have an array 
if(itemArrayObj.isArray()) 
{ 
    // get the array as a JsonArray 
    QJsonArray itemArray = itemArrayObj.toArray(); 
} 

당신이 모르는 경우 형식을 사용하려면 각 QJsonObject에 해당 유형을 요청하고 이에 따라 대응해야합니다. QJsonValue의 타입을 배열, int 등 올바른 객체로 변환하기 전에 QJsonValue의 유형을 확인하는 것이 좋습니다.