This piece of code is usable when you need Stream object which has to store/load data to/from Arduino String object.
#ifndef _STRING_STREAM_H_
#define _STRING_STREAM_H_
#include <Stream.h>
class StringStream : public Stream
{
public:
StringStream(String *s) : string(s), position(0) { }
// Stream methods
virtual int available() { return string->length() - position; }
virtual int read() { return position < string->length() ? (*string)[position++] : -1; }
virtual int peek() { return position < string->length() ? (*string)[position] : -1; }
virtual void flush() { };
// Print methods
virtual size_t write(uint8_t c) { (*string) += (char)c; return 1;};
private:
String *string;
unsigned int length;
unsigned int position;
};
#endif // _STRING_STREAM_H_
Example with ArduinoJsonWriter library...
#include <JsonWriter.h>
#include "StringStream.h"
void setup() {
Serial.begin(9600);
String output;
StringStream stream(&output);
JsonWriter streamJsonWriter(&stream);
streamJsonWriter
.beginArray()
.beginObject()
.property("name", "alpha")
.endObject()
.beginObject()
.property("name", "beta")
.property("anotherProperty", 12.67)
.endObject()
.beginObject()
.property("name", "gamma")
.endObject()
.endArray();
Serial.println(output);
}
void loop() {}
BSD Zero Clause License
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED “AS IS” AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE
FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY
DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
This was helpful -- thanks! I'm a little surprised the constructor takes a String* rather than a String&, but that's a very minor issue.