问题
I have the following code which should read the contents of a text file and parse it as JSON
try {
string_t importFile = argv[++iArgCounter]; // extract filename
ifstream_t f(importFile); // filestream of working file
stringstream_t s; // string stream for holding JSON read from file
json::value v; // JSON read from input file
iArgCounter++; // increment arg counter
if (f) {
s << f.rdbuf(); // stream results of reading from file stream into string stream
f.close(); // close the filestream
v.parse(s); // parse the resultant string stream.
}
}
catch (web::json::json_exception excep) {
std::cout << "ERROR Parsing JSON: ";
std::cout << excep.what();
break;
}
And the following test JSON file
[
{
"Destinations":
[
{
"Domain": "127.0.0.1",
"Name": "GoogleLogin",
"Port": "8090"
}
],
"Listeners":
[
{
"Domain": "127.0.0.1",
"Name": "LoginRequest",
"Port": "8080",
"Route": "ProcessLoginRequest"
}
],
"Name": "LoginProcess",
"Routes":
[
{
"Name": "ProcessLoginRequest",
"Rules":
[{
"DestinationIfTrue": "GoogleLogin",
"LeftTerm":
{
"RuleTermType": 1,
"Value": "NETWORK"
},
"Operator": 2,
"RightTerm":
{
"RuleTermType": 0,
"Value": "NETWORK"
}
}],
"Transformations": []
}
]
}
]
The trouble is no matter what the JSON code I get the error 'Line 1, Column 2 Syntax error: Malformed token'. From what I can tell the JSON is correctly formatted with all brackets balanced.
Code is running on 64bit Windows 7.
Anyone got an idea why it thinks this (or how I can convert the stringstream_t to a string and see what it actually reads).
回答1:
- Could it be that the file is of utf16 encoding?
- Or check if your json file has BOM (Byte Oder Mark) at the head by opening it with a hex editor.
回答2:
change the line
v.parse(s);
to
v = json::value::parse(s)
来源:https://stackoverflow.com/questions/28972751/reading-json-from-a-file-using-c-rest-sdk-casablanca