Arduino JSON package - formatting sensor value - json

#include <ArduinoJson.h>
#include <SimpleDHT.h>
String input = "{\"temperature\":\"26\"};
SimpleDHT11 dht11;
byte temperature = 0;
int err = SimpleDHTErrSuccess;
void loop {
StaticJsonBuffer<512> dataBuffer;
if (err = dht11.read(2, &temperature, NULL)) == simpleDHTErrSuccess) {
Serial.print((int) temperature);
JsonObject& dataRoot = dataBuffer.parseObject(input);
*long Temperature = dataRoot[String("temperature")];
*Temperature = (long)temperature;
*dataRoot[String("temperature")] = Temperature;
String output;
dataRoot.printTo(output);
}
I have here a snippet of Arduino code used to format a DHT11 temperature sensor readings in JSON, to allow for live streaming of the data on a web client. This was obtained from this project I am using for inspiration https://www.twilio.com/blog/2018/07/watch-iot-sensors-esp32-javascript-nodejs-twilio-sync.html.
I am instead attempting to pull data from a Myoware muscle sensor. The amplitude value I am wanting can simply be queried like so:
int sensorValue = analogRead(A0);
I need help in understanding how the parseObject function works and what the purpose of the 'input' string is. All I want is for my sensor's value to be fed to the client side which displays it in a graph. The three lines I have asterisked are particularly confusing.
Thanks!

The method parseObject() allocates and populate a JsonObject (that you can work with) from a JSON string.
The "JsonObject" in your code example is named dataRoot and is defined with
JsonObject& dataRoot = dataBuffer.parseObject(input);
where dataBuffer comes from StaticJsonBuffer<512> dataBuffer; which is the entry point for using the ArduinoJson library, and
where input has the value of the JSON string "{\"temperature\":\"26\"}" which follows the standard JSON attribute-value pair format (you need a JSON string to work with and then send it to the client side).
After JsonObject& dataRoot = dataBuffer.parseObject(input); is executed, you get dataRoot as an object with a property named temperature and you can access this property with dataRoot[String("temperature")]
So the three lines:
long Temperature = dataRoot[String("temperature")];
Temperature = (long)temperature;
dataRoot[String("temperature")] = Temperature;
are used to update the value of the temperature attribute with whatever is read from the sensor.
A bit confusing in the example code is the fact that the name of the JSON attribute is temperature and also the name for the variable to hold the temperature read from sensor is also temperature. They are different things.

Related

json-c json_object_to_json_string() equivalent api in jansson library

In the Current code i'm using json-c. i'm migrating to jansson.
need an equivalent api in jansson which converts the json_object_to_json_string.
i found one but it needs a json string object otherwise it is returning null.
const char *json_string_value(const json_t *string) - not working
but my input is a JSON object not a JSON string
sample:
json_object *jobj = json_object_new_object();
....
const char *final_string = json_object_to_json_string(jobj);
Thanks.
I was in your position just recently, I believe the function you are looking for is:
char *json_dumps(const json_t *json, size_t flags)
Returns the JSON representation of json as a string, or NULL on error. flags is described above. The return value must be freed by the caller using free().
https://jansson.readthedocs.io/en/2.8/apiref.html#c.json_dumps

Parsing JSON Data from URL with Android Studio

I'm trying to parse JSON data from URL and show the data in my app.
JSON Example (After accessing specific URL):
[{"placeID":"1","placeName":"Test Place","city":"New York","type":"Rest"..
How I can read this data and show a list of the places recieved from the API?
I've been trying ALL of the guides over the internet for parsing JSON data from URL with Android Studio and without. As a total beginner with Android developement, I couldn't make one working exmaple with json even when the author shared the final example for download. I hope you can help me in noob-friendly way and step by step or refer me to the right places.
Thank you!
I believe Android uses org.json as the JSON library, in which case something like this works to retrieve information about each place (assuming data is a valid JSON string)
try {
String data = "\"[{\"placeID\":\"1\",\"placeName\":\"Test Place\",\"city\":\"New York\",\"type\":\"Rest\"..";
JSONArray places = new JSONArray(data);
for (int i = 0; i < places.length(); i++)
JSONObject place = (JSONObject) places.get(i);
int id = place.getInt("id");
String name = place.getString("placeName");
String city = place.getString("city");
// etc...
// Do what you wish with the id, name, city and other variables.
// It loops through here for each item in the JSON variable.
}
} catch (JSONException e) {
e.printStackTrace();
}
This goes through each place in the JSON array and grabs some of the variables from it. It would probably be smart to create a data class and call it something like Place. You could then pass in the data with a constructor: new Place(id, name, city); (see this constructor for example: https://stackoverflow.com/a/22419370/5236779).

parse json file from internet (with lots of quotes: " (not \")) with the Arduino JSON library

i need to parse a json file from the internet with my arduino uno r3
(i cannot change the output / file), i have to use it as it is...
My json file i get from the internet looks like this: (example from https://github.com/bblanchon/ArduinoJson)
char json[] = "{"sensor":"gps","time":1351824120,"data":[48.756080,2.302038]}";
The problem are the quotes "" inside the brackets,
If i change all quotes to \" everything works:
I provide an working Example from ArduinoJson library page:
char json[] = "{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}";
StaticJsonBuffer<200> jsonBuffer;
JsonObject& root = jsonBuffer.parseObject(json);
const char* sensor = root["sensor"];
long time = root["time"];
double latitude = root["data"][0];
double longitude = root["data"][1];
QUESTION:
How to replace the quotes, change them on the fly, or create the variable directly without the quotes, i need to parse the content afterwards.
Your problem is how you get the data from the client.
You only read one char and not all the data.
Try something like this:
I don't have a wifi or ethernet shield I cannot test, so I don't know if your lib will skip the http headers.
Try to print data after the loop to check.
char data[1024];
void loop(void ) {
int pos = 0;
memset(&data, 0, sizeof(data));
/* here your code for the GET
client.println("GET live.kvv.de/webapp/departures/bystop/…);
*/
while (client.available() && pos < sizeof(data) - 1) {
data[pos++] = client.read();
}
/* now you have all the data
XXX: check if you need to skip http headers
TODO: trigger an error is data is too small
*/
jsonBuffer.parseObject(data);

ServiceStack/Redis with Json over Http returns string not Json

I am trying to get CouchDB-like response from Redis - by using ServiceStack WebServices to access data stored via ServiceStack .Net RedisTypedClient onto Redis.
Now the web services are described as providing a CouchDB layer onto Redis. However, unlike equivalent CouchDB calls to a CouchDB, I never get back json but only strings - to be clear I do get back json but with the payload is in string format.
This applies to getting items from Redis List, Set and HashSet collections. All the items via either the xml,json or csv web services always deliver the payload as a string. Now I can see the serialized form of the type I stored in the string - such as a json array of strings or whatever, but the data is not delivered as json (or csv or xml) but as a string. I cannot find a query flag (.e.g. 'format=json' say) in any of the autogenerated documentation for these web services -which does say it delivers the payload as a string which is what I see.
Further apart from using the default jsv serializer through RedisTypedCLient I also tried directly calling the ServiceStack json serializer to serialize as json not jsv and also the Newtonsoft json serializer. None of this makes any difference. I did not expect it too as I imagine the default services would likely only manage the expected jsv version and would deliver anything else as strings. However I did not expect this of the internal serialization format.
So is it possible to get CouchDB like json responses from ServiceStack/Redis/Builtin-WebServices?
Update
Here is a typical query via the ServiceStack json web service:
http://myserver.com/redis/json/syncreply/GetAllItemsFromList?id=test
This is a Redis List collection containing strongly typed items:
type TestItem( gr,eType,pillar,offset) =
let mutable _gr = gr
let mutable _eType = eType
let mutable _pillar = pillar
let mutable _offset = offset
member x.Gr with get()= _gr and set(v) = _gr <- v
member x.EType with get()= _eType and set(v) = _eType <- v
member x.Pillar with get()= _pillar and set(v) = _pillar <- v
member x.Offset with get()= _offset and set(v) = _offset <- v
override x.ToString() = sprintf "%s %s %s %M" x.Gr x.EType x.Pillar x.Offset
The list collection was added using IRedisTypedClient Interface/API and I am expecting back a json list of json objects - a set of key/value pairs each pair corresponding to one of the four public properties in the type above. Instead I get
{"Items":[" {\"Gr\":\"BON13\",\"EType\":\"MARKET\",\"Pillar\":\"BON3.R0\",\"Offset\":0.0}","{\"Gr\":\"BOQ13\",\"EType\":\"MARKET\",\"Pillar\":\"BOQ3.R0\",\"Offset\":0.0}","{\"Gr\":\"BOU13\",\"EType\":\"MARKET\",\"Pillar\":\"BOU3.R0\",\"Offset\":0.0}","{\"Gr\":\"BOV13\",\"EType\":\"SETTLEPILLAR\",\"Pillar\":\"BOU3.R0\",\"Offset\":0.0}","{\"Gr\":\"BOZ16\",\"EType\":\"SETTLEPILLAR\",\"Pillar\":\"BOU3.R0\",\"Offset\":0.0}"],"ResponseStatus":{}}
In other words a string representation of the json object not the json object itself.
So again, how can I get back, in this case, a json list of of json objects rather than a json list of strings. (And the same goes for Sets, Dictionaries and more basic keyed json documents a la other NoSql dbs)?
I have the same issues getting back csv - it comes back as a string rather than either a csv of key/value pairs or a csv of keys and values and in XML where this,again, comes back as a string not not an XML format of key/value pairs.
Update 1
It does not need to be a strongly typed as above. It could be a list of a list of strings. In which case I get back a json list of strings rather than a json list containing items comprising json list of string.
Update 2
Whilst the problem clearly seems to be in the ServiceStack webservice implementation not being like CouchDB although it claims it is, here is some sample code to put the data into Redis via ServiceStack.
open System
open System.Collections.Generic
open ServiceStack.Redis
open System.Linq
type Repository() =
static let mutable __port = 6379
static let mutable __host = "myserver.com"
static let mutable __client = new RedisClient(__host,__port)
static member Client = __client :> IRedisClient
type Repository<'T>() =
let _client = Repository.Client
member x.GetList key =
use client = _client.As<'T>()
match _client.GetEntryType key with
| RedisKeyType.List ->
client.Lists.Item key |> client.GetAllItemsFromList
| _ -> new List<'T>()
member x.SetList (key, values: List<'T>) =
if (values.Count <> 0) then
use client = _client.As<'T>()
let list = client.Lists.Item key
values |> Seq.iter (fun x -> client.AddItemToList(list, x))
Usage
let repo = new Repository<List<string>>
let items = [["key0";"data0"];["key1";"data1"]]
|> Seq.map (fun kd -> List.init kd ))
|> List.init
repo.SetList("test",items)
The is just a cut and paste of longer code. I have tried this in c#, f# and with non default serialization as already stated. That is I have tried six different methods to date and none delivered the data payload as json objects via ServiceStack WebServices only as strings.
JSON data, when serialized and sent over the wire, is just a string. Your client needs to be JSON aware and de-serialize it into your object. The JsonClient for C# within ServiceStack is more than capable of handling this, and so are the many JavaScript frameworks that assist with AJAX calls (jQuery, AngularJS, etc).

problems reading int from bytearray

This is my first question, so do not judge strictly.
I have an object that I'm getting from php server to as3(flash) client. That object is AMF encoded, so I write server response to ByteArray:
var ba:ByteArray = new ByteArray();
ba.writeUTFBytes( rawData );
and than I'm reading object from ByteArray:
ba.position = 0;
var response:Object = ba.readObject();
Part of object contains such data:
{
'money' : 900
}
And when reading object from ByteArray, I get a seven-digit number ~ 1824344 instead of 900. But when I get form server String '900' or int value equals 100 - data reads correctly.
Has someone had such a problem?
You have to read the same way you wrote. If you write something using writeUTFBytes(), you have to read it using readUTFBytes().
In this case you should use writeObject() and readObject() because you are writing pure Object but not String.