C++json解析
代码示例:
#include <iostream>
#include <string>
#include <jsoncpp/json/json.h>
using namespace std;
int main()
{
string strJsonContent = "{\"role_id\": 1,\"occupation\": \"paladin\",\"camp\": \"alliance\"}";
int nRoleDd = 0;
string strOccupation = "";
string strCamp = "";
Json::Reader reader;
Json::Value root;
if (reader.parse(strJsonContent, root))
{
nRoleDd = root["role_id"].asInt();
strOccupation = root["occupation"].asString();
strCamp = root["camp"].asString();
}
cout << "role_id is: " << nRoleDd << endl;
cout << "occupation is: " << strOccupation << endl;
cout << "camp is: " << strCamp << endl;
return 0;
}
json格式转换方法
JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,通过文本格式进行数据的传输和存储。下面是三种常用的JSON格式转换方法:
1. 使用编程语言的JSON解析库来进行转换,如Python中的`json`包、Java中的`Gson`库、JavaScript中的`JSON`对象等。
2. 在线的JSON格式转换工具,如https://www.json.cn/、https://www.bejson.com/json/jsonencode/.
3. 手动编写转换代码,将JSON字符串解析为对象,然后进行对象操作,最后将对象转换为JSON字符串。这种方法需要对JSON格式有一定的了解。下面是Java代码示例:
```
import com.alibaba.fastjson.JSON;
// JSON字符串
String jsonString = "{\"name\":\"Tom\",\"age\":20}";
// 将JSON字符串解析为对象
User user = JSON.parseObject(jsonString, User.class);
// 对象操作
user.setAge(21);
// 将对象转换为JSON字符串
String newJsonString = JSON.toJSONString(user);
```
还没有评论,来说两句吧...