所以我通过SPI从传感器读取一些值。我已经将这些值转换为字符串(不知道我应该,但我正在尝试一些东西)。现在我无法将它们转换为json格式。 这是我的代码:
#include "ad7490Spi.h"
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
string IntToString (int a2dVal)
{
ostringstream oss;
oss << a2dVal;
return oss.str();
}
int main(void)
{
ad7490Spi a2d("/dev/spidev0.0", SPI_MODE_0, 1000000, 16);
int i = 5;
int a2dVal = 0;
int a2dChannel = 0;
unsigned char data[3];
while(i > 0)
{
data[0] = 1; // first byte transmitted -> start bit
data[1] = 0b1000000000000000 |( ((a2dChannel & 15) << 4)); // second byte transmitted -> (SGL/DIF = 1, D2=D1=D0=0)
data[2] = 0; // third byte transmitted....don't care
a2d.spiWriteRead(data, sizeof(data) );
a2dVal = 0;
a2dVal = (data[1]<< 8) & 0b1100000000; //merge data[1] & data[2] to get result
a2dVal |= (data[2] & 0xff);
sleep(1);
i--;
string result = IntToString (a2dVal);
cout << " " + result + " ";
}
return 0;
}
结果如下:
1023 1023 1023 1023 1023
我希望结果是这样的:
{
"values": [ "1023", "1023", "1023", "1023", "1023" ]
}
你们能帮助我吗?
答案 0 :(得分:0)
此代码:
#include <iostream>
#include <string>
#include <iomanip>
#include <vector>
void print_values(std::ostream& os, const std::vector<int>& v)
{
using namespace std;
os << "{\n";
os << "\t\"values\" : [";
auto sep = " ";
for (const auto& i : v) {
os << sep << quoted(to_string(i));
sep = ", ";
}
os << " ]\n";
os << "}\n";
}
auto main() -> int
{
print_values(std::cout, {1,2,3,4,5,6});
return 0;
}
结果:
{
"values" : [ "1", "2", "3", "4", "5", "6" ]
}
更新
这个版本将使用c ++ 11编译器正常运行(并突出显示c ++ 14的一些新特性 - 但是让我们不会在石器时代生活太久呃? )
#include <iostream>
#include <string>
#include <iomanip>
#include <vector>
#if __cplusplus >= 201402L
#else
std::string quoted(const std::string& s) {
using namespace std;
return string(1, '"') + s + '"';
}
#endif
void print_values(std::ostream& os, const std::vector<int>& v)
{
using namespace std;
os << "{\n";
os << "\t\"values\" : [";
auto sep = " ";
for (const auto& i : v) {
os << sep << quoted(to_string(i));
sep = ", ";
}
os << " ]\n";
os << "}\n";
}
auto main() -> int
{
using namespace std;
print_values(cout,
#if __cplusplus >= 201402L
{1,2,3,4,5,6}
#else
[]() -> vector<int> {
vector<int> v;
for (int i = 1 ; i < 7 ; ++i )
v.push_back(i);
return v;
}()
#endif
);
return 0;
}
答案 1 :(得分:0)
由于您似乎在嵌入式系统中使用C ++和STL,我建议您使用picojson。它只是一个1头文件库,并且比使用一些字符串操作自己实现序列化更好。如果你这样做,如果扩展你的json输出,它将会变得更加丑陋。