From dfeccf7ffc1f6f18624d901f2762c733a81fc024 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20Blanchon?= Date: Tue, 15 Mar 2016 10:26:17 +0100 Subject: [PATCH] Updated FAQ (markdown) --- FAQ.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/FAQ.md b/FAQ.md index a86901b..f006ef5 100644 --- a/FAQ.md +++ b/FAQ.md @@ -345,6 +345,33 @@ Reusable | no(3) | no(3) As a general rule, if your `StaticJsonBuffer` is bigger than 2K, then it may be a good time to switch to a `DynamicJsonBuffer`. +### How to determine the buffer size? + +There are basically tree approaches here: + +1. either you can predict the content of the object tree, +2. you know how much memory is available. +3. you try and look at current size + +In the first case, you know some constraints on the object tree. For instance, let's say that you know in advance (and by that I mean "at compilation time") that you want to generate an object with 3 values, one of them being an array with 2 values, like the following: + + {"sensor":"gps","time":1351824120,"data":[48.756080,2.302038]} + +To determine the memory usage of this object tree, you use the two macros `JSON_ARRAY_SIZE(n)` and `JSON_OBJECT_SIZE(n)`, both take the number of elements as an argument. +For the example above, it would be: + + const int BUFFER_SIZE = JSON_OBJECT_SIZE(3) + JSON_ARRAY_SIZE(2); + StaticJsonBuffer jsonBuffer; + +In the second case, let's say you dynamically generate a JSON object tree of a random complexity so you can't put a limit based on that. But on the other hand, you don't want your program to crash because the object tree doesn't fit in memory. +The solution here is to determine how much memory is available, or in other words how much memory you can afford for the JSON object tree. + +The third solution is to run your program an print `jsonBuffer.size()` to get the current size of the buffer. + +**WARNING**: if you use `String` to create your JSON keys or values, there content will automatically be duplicated in the `JsonBuffer`, so you need to add the total length of all strings in the size of the `JsonBuffer`. + +See issue [#243](https://github.com/bblanchon/ArduinoJson/issues/243#issuecomment-196553398) + ### I found a memory leak in the library! This is very unlikely. You're probably using the library incorrectly.