libjson

libjson_7.3.2


示例1:

 调用GetSwfAddress ,取出json中指定域的值

#include "libjson/libjson.h"

string DataLoaderController::ParseJSON(const JSONNode &n ) {
  string ret = "";
  JSONNode::const_iterator i = n.begin();
  while (i != n.end()) {
    if (i -> type() == JSON_ARRAY || i -> type() == JSON_NODE) {
       ret = ParseJSON(*i);
    }   
    if (ret != "")
      break;  
    std::string node_name = i -> name();
    if (node_name == "meta") {
      ret = i->as_string();
      break;
    }   
    ++i;
  }
  return ret;  
}

string DataLoaderController::GetSwfAddress(const std::string &data) {
  string flash_url;
  JSONNode n = libjson::parse(data);
  string meta_content = ParseJSON(n);  //递归找json串中的meta字段

/*

  size_t head_pos = meta_content.find("\"flash_url\":\"",0);
  if (head_pos == string::npos)
    return "";
  size_t rear_pos = meta_content.find("\",\"width\"");
  if (rear_pos == string::npos)
    return "";
  string flash_url_raw  = meta_content.substr(head_pos+13,rear_pos-head_pos-13);
  ostringstream ss;
  for (size_t i =0; i<flash_url_raw.length(); ++i)
    if (flash_url_raw[i] != '\\')
      ss << flash_url_raw[i];
*/
  return ss.str();
}

示例 2:

void DataProviderController::ParsePhotoJSON(const JSONNode &n,  vector<PhotoInfo> &photoInfoVec) {
  PhotoInfo pi;
  JSONNode::const_iterator i = n.begin();
  while (i != n.end()){
    if (i -> type() == JSON_ARRAY || i -> type() == JSON_NODE){
      ParsePhotoJSON(*i, photoInfoVec);
    }   
    std::string node_name = i -> name();
    if (node_name == "headUrl")
      pi.headUrl = i->as_string();
    else if (node_name == "largeUrl")
      pi.largeUrl = i->as_string();
    else if (node_name == "atTitle")
      pi.atTitle = i->as_string();
    else if (node_name == "linkUrl")
      pi.linkUrl = i->as_string();
    else if (node_name == "id")
      pi.photoId = i->as_string();
    ++i;
  }
  if (pi.headUrl!="" && pi.largeUrl!="" && pi.linkUrl!="" && pi.photoId!="")
    photoInfoVec.push_back(pi);
}
 
void DataProviderController::GetPhotoInfo(const string photo_list_json, vector<PhotoInfo> &photoInfoVec) {
  JSONNode n = libjson::parse(photo_list_json);
  ParsePhotoJSON(n, photoInfoVec);
}




你可能感兴趣的:(libjson)