How to pass single element JSON arrays using webwrite
Show older comments
Hi,
The question in brief:
"Can anyone advise how to pass single element JSON arrays using webwrite, and how to have them interpreted as integers rather than doubles?"
The problem:
I'm trying to pass a JSON value to an external API, over which I have no control.
The API wants to see:
{
"method": "blahblah",
"params": [1],
"id": 1,
"version": "1.0"
}
Which is confirmed to work. I know a single value array is maybe a bit silly. But it is what is required. And the API rejects a single number value without the square brackets.
In order to pass that to the external API, I am using webwrite
method = 'blahblah';
params = [1];
id = 1;
version = '1.0';
data = struct('method',method,'params',params, 'id',id,'version',version);
options = weboptions('MediaType','application/json');
response = webwrite('URL',data,options)
This generates the following JSON output:
{"method":"blahblah","params":1,"id":1,"version":"1.0"}
As you can see, everything is great except for the single element array value for "params", which is just a number instead of an array.
i.e
"params":1 % which I don't want (doesn't work)
instead of
"params": [1] % which I do want (works)
Drilling down, the matlab-json converter used by webwrite is
mls.internal.toJSON
We can see the function writes JSON arrays when it is passed arrays (although it converts them to doubles, which my API doesn't like at all):
>> mls.internal.toJSON(struct('params',[2,3]))
ans =
{"params":[2.0000000000000000,3.0000000000000000]}
But when passed a single value, it reverts to passing a simple JSON number, rather than a single element array:
>> mls.internal.toJSON(struct('params',[2]))
ans =
{"params":2}
It looks like similar problems have existed elsewhere: (Java) http://stackoverflow.com/questions/17003823/make-jackson-interpret-single-json-object-as-array-with-one-element
Can anyone advise how to pass single element JSON arrays using webwrite, and how to have them interpreted as integers rather than doubles?
Any assistance hugely appreciated.
Accepted Answer
More Answers (0)
Categories
Find more on JSON Format in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!