2013-06-12 3 views
2

main 함수에 정의 된 JSON Stinrg에서 배열을 가져 오려고합니다. 나는 이것을 위해 libjson API를 사용했다. 간단한 키 값을 얻기 쉽기 때문에 RootA의 값을 얻을 수 있지만 ChildA의 배열에 대해서는 어떨까? 날이 아마 당신이 찾고 있던 답하지JSON 문자열 배열을 가져 오는 중 오류가 발생했습니다.

#include <iostream> 
#include <libjson/libjson.h> 
#include <stdio.h> 
#include <string.h> 

using namespace std; 

char rootA[20]; 
int childB; 
int *childInt; 

void ParseJSON(JSONNODE *n) { 
    if (n == NULL) { 
     printf("Invalid JSON Node\n"); 
     return; 
    } 

    JSONNODE_ITERATOR i = json_begin(n); 
    while (i != json_end(n)) { 
     if (*i == NULL) { 
      printf("Invalid JSON Node\n"); 
      return; 
     } 

     // recursively call ourselves to dig deeper into the tree 
     if (json_type(*i) == JSON_ARRAY || json_type(*i) == JSON_NODE) { 
      ParseJSON(*i); 
     } 

     // get the node name and value as a string 
     json_char *node_name = json_name(*i); 

     // find out where to store the values 
     if (strcmp(node_name, "RootA") == 0) { 
      json_char *node_value = json_as_string(*i); 
      strcpy(rootA, node_value); 
      cout << rootA<<"\n"; 
      json_free(node_value); 
     } else if (strcmp(node_name, "ChildA") == 0) { 
      JSONNODE *node_value = json_as_array(*i); 

      childInt=reinterpret_cast<int *>(&node_value); 
      cout << childInt[0]<<"\n"; 
      cout << childInt[1]<<"\n"; 
      json_free(node_value); 
     } else if (strcmp(node_name, "ChildB") == 0) { 
      childB = json_as_int(*i); 
      cout << childB; 
     } 
     // cleanup and increment the iterator 
     json_free(node_name); 
     ++i; 
    } 
} 

int main(int argc, char **argv) { 
    char 
      *json = 
        "{\"RootA\":\"Value in parent node\",\"ChildNode\":{\"ChildA\":[1,2],\"ChildB\":42}}"; 
    JSONNODE *n = json_parse(json); 
    ParseJSON(n); 
    json_delete(n); 
    return 0; 
} 

답변

1

감사하지-sehe하지만 난 노드로이

좋아 겠어요 ... 치료 배열에 대한 솔루션을 가지고 및 반복 마치 그것의 빈 키가있는 값. 당신은 그것을 한 코드 부분을 볼 수 있습니다 ..

if (json_type(*i) == JSON_ARRAY) { 
    cout << "\n Its a Json Array"; 
    JSONNODE *arrayValue = json_as_array(*i); 
    JSONNODE_ITERATOR i1 = json_begin(arrayValue); 
    while (i1 != json_end(arrayValue)) { 
      cout << "\n In Array Loop "; 
     cout << json_as_int(*i1); 
     ++i1; 
    } 
} 
0

을 알려하지만, 나 그냥 조금 더 현대적인 인터페이스와 라이브러리를 만드는 것을 보여주세요 (test.cpp)이 훨씬 쉬워 :

#include <sstream> 
#include "JSON.hpp" 

int main() 
{ 
    auto document = JSON::readFrom(std::istringstream(
       "{\"RootA\":\"Value in parent node\",\"ChildNode\":{\"ChildA\":[1,2],\"ChildB\":42}}")); 

    auto childA = as_object(
       as_object(document)[L"ChildNode"] 
      )[L"ChildA"]; 

    std::cout << childA << std::endl; 
} 
그것은 rfc4627 specs 내 자신의 미니멀 구현을 사용하고

[1,2] 

인쇄

. 인터페이스만으로 미니멀리즘이며 전체 구문과 유니 코드를 지원합니다.

이 API 인터페이스는 매우 제한적입니다,하지만 당신은 등 적절한 사전 조회, 키 비교로, C 스타일의 포인터없이 작업하는 그것 경향이 덜 지루하고 오류하게 볼 이미 수 있습니다

// or use each value 
for(auto& value : as_array(childA).values) 
    std::cout << value << std::endl; 

// more advanced: 
JSON::Value expected = JSON::Object { 
    { L"RootA", L"Value in parent node" }, 
    { L"ChildNode", JSON::Object { 
      { L"ChildA", JSON::Array { 1,2 } }, 
      { L"ChildB", 42 }, 
     } }, 
}; 
std::cout << "Check equality: " << std::boolalpha << (document == expected) << std::endl; 
std::cout << "Serialized: " << document; 

참조 전체 파서 구현 : GitHub의에서 (주 너무 직렬화를 포함) : https://github.com/sehe/spirit-v2-json/tree/q17064905

관련 문제