ArduinoJson不会反序列化从HTTP GET读取的字符串,但会反序列化字符串文字

时间:2019-06-26 15:41:39

标签: json string serialization arduino

我正在使用ESP8266向https://openaq.org/提供的APi发出HTTP GET请求,然后使用ArduinoJson https://arduinojson.org/库对数据进行反序列化并提取传感器读数。

我可以获得Json数据并打印出字符串,但是当我尝试反序列化时,它不起作用

如果我将打印的输出复制并粘贴到串行监视器中,然后粘贴回代码中,然后将其反序列化,则它可以正常工作,请参见当前注释行

//line = "{\"meta\":{\"name\":\"openaq-api\",\"license\":\"CC BY 4.0\",\"website\":\"https://docs.openaq.org/\",\"page\":1,\"limit\":1,\"found\":1955},\"results\":[{\"location\":\"Birmingham Acocks Green\",\"parameter\":\"pm25\",\"date\":{\"utc\":\"2019-06-26T12:00:00.000Z\",\"local\":\"2019-06-26T13:00:00+01:00\"},\"value\":5,\"unit\":\"µg/m³\",\"coordinates\":{\"latitude\":52.437165,\"longitude\":-1.829999},\"country\":\"GB\",\"city\":\"Birmingham\"}]}";

我认为起初可能是需要转义的“”,但这并没有什么不同。 我还认为这可能是因为该字符串没有空终止符,因此无法正常工作,但尝试将一个字符串连接到末尾

line = line + "";

但同样没有效果

void setup() {


const char* host = "api.openaq.org";
const int httpsPort = 443;

const char* fingerprint = "47 03 D4 71 84 CD E2 47 5D 4C 04 52 61 28 83 84 E6 FF 66 53";
String url = "/v1/measurements?location=Birmingham%20Acocks%20Green&parameter=pm25&limit=1";
  // put your setup code here, to run once:
    Serial.begin(115200);

  /*
   * 
   * 
   * Connect to Wifi
   * 
   */


  Serial.println();
  Serial.print("connecting to ");
  Serial.println(ssid);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());


  //Attempt to connect to the host and port specified
  WiFiClientSecure client;
  Serial.print("Connecting to ");
  Serial.println(host);
  if (!client.connect(host, httpsPort)){
    Serial.println("Connection failed");
    return;
  }

   //Compare the Certificate returned with the one we manually obtained
   if (client.verify(fingerprint, host)) {
    Serial.println("certificate matches");
  } else {
    Serial.println("certificate doesn't match");
    return;
  }

  Serial.print("Requesting url ");
  Serial.println (url);

    client.print(String("GET ") + url + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" +
               "User-Agent: ArduinoESP8266\r\n" +
               "Connection: close\r\n\r\n");

  Serial.println("request sent");


   // Check HTTP status
  char status[32] = {0};
  client.readBytesUntil('\r', status, sizeof(status));
  // It should be "HTTP/1.0 200 OK" or "HTTP/1.1 200 OK"
  if (strcmp(status + 9, "200 OK") != 0) {
    Serial.print(F("Unexpected response: "));
    Serial.println(status);
    return;
  }

  // Skip HTTP headers
  char endOfHeaders[] = "\r\n\r\n";
  if (!client.find(endOfHeaders)) {
    Serial.println(F("Invalid response"));
    return;
  }

  String line = client.readStringUntil('\n');
  String toReplace = "\"";
  String replacedBy = "\\\"";
  line.replace(toReplace, replacedBy);



  //line = "{\"meta\":{\"name\":\"openaq-api\",\"license\":\"CC BY 4.0\",\"website\":\"https://docs.openaq.org/\",\"page\":1,\"limit\":1,\"found\":1955},\"results\":[{\"location\":\"Birmingham Acocks Green\",\"parameter\":\"pm25\",\"date\":{\"utc\":\"2019-06-26T12:00:00.000Z\",\"local\":\"2019-06-26T13:00:00+01:00\"},\"value\":5,\"unit\":\"µg/m³\",\"coordinates\":{\"latitude\":52.437165,\"longitude\":-1.829999},\"country\":\"GB\",\"city\":\"Birmingham\"}]}";

  Serial.println(line);
  int line_len = line.length() + 1;
  char char_array[line_len];

  line.toCharArray(char_array,line_len);


  //send the String object to the input of the DeserializeJson
  DynamicJsonDocument doc(1200);
  deserializeJson(doc,char_array);
  JsonObject obj = doc.as<JsonObject>();

  String nameAQ = obj[String("meta")];

  Serial.println(nameAQ);

  JsonArray results = obj["results"];
  JsonObject results_0 = results[0];

  int results_0_value = results_0["value"];

  Serial.println(results_0_value);


}

当我Serial.print()时,我希望返回的元内容 {“ name”:“ openaq-api”,“许可证”:“ CC BY 4.0”,“网站”:“ https://docs.openaq.org/”,“页面”:1,“限制”:1,“找到”:1955 } 但输出为空

当我Serial.print()的结果_0_value int时,我希望它返回JSON中的任何值,但它输出0

1 个答案:

答案 0 :(得分:0)

已设法解决此问题。我删除了几行以转义JSON中的“

import cv2
import numpy as np
import sys
from IPython.display import Image
from matplotlib import pyplot as plt
import numpy
import os


img = cv2.imread('C:\\Users\\not-cropped.jpg')
gray= cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

search_params = dict(checks = 50)

FLANN_INDEX_LSH = 6
index_params= dict(algorithm = FLANN_INDEX_LSH,
                   table_number =12 , # 12
                   key_size = 20,     # 20
                   multi_probe_level = 2) #2



# Initiate STAR detector
star = cv2.xfeatures2d.StarDetector_create()
# Initiate BRIEF extractor
brief = cv2.xfeatures2d.BriefDescriptorExtractor_create()

# find the keypoints with STAR
kp_brief_o = star.detect(gray,None)

# compute the descriptors with BRIEF
kp_brief_o, des_brief_o = brief.compute(gray, kp_brief_o)


img66 = cv2.drawKeypoints(gray,kp_brief_o,None,(255,0,0),4)
plt.imshow(img66),plt.show()
##########################################################33
gray_crop = cv2.imread('C:\\Users\\cropped.jpg', 0)

kp_brief_crop = star.detect(gray_crop,None)

kp_brief_crop, des_brief_crop = brief.compute(gray_crop, kp_brief_crop)

flann = cv2.FlannBasedMatcher(index_params, search_params)
matches = flann.knnMatch(des_brief_o, des_brief_crop, k=2)

good = []
for m,n in matches:
    if m.distance < 0.7*n.distance:
    good.append(m)

我在开发中将它们放在较早的版本中以解决问题,我认为较早的问题是其他问题,但留给了它们。它们看起来像是必需的,如ArduinoJSon Assistant https://arduinojson.org/v6/assistant/中所示