behzad behzad - 3 months ago 18
JSON Question

Wrong conversion from struct to JSON by MATLAB

I want to communicate with a web server using the MATLAB's webwrite function. here is what I found problematic:

imagine a struct like this: 1x1 struct with 3 fields

test1x1 =

a: 'a'
b: 'b'
c: 'c'


pay attention that
test1x1
is a 1x1 struct with 3 fields

now I have another struct, lets call it
test1x2
, this one is a 1x2 struct with 3 fields

test1x2 =

1x2 struct array with fields:

a
b
c

>> test1x2(1)

ans =

a: 'a'
b: 'b'
c: 'c'

>> test1x2(2)

ans =

a: 'a2'
b: 'b2'
c: 'c2'


now I want to sent
test1x1
as JSON to my webserver

response = webwrite('aURL',test1x1 , weboptions('MediaType','application/json'));


if you use the debugger, somewhere in the
webwrite
function you can see the pure JSON which will be sent to server, here is the generated JSON:

{"a":"a","b":"b","c":"c"}


and now ,
test1x2
will generate the following JSON:

[{"a":"a","b":"b","c":"c"},{"a":"a2","b":"b2","c":"c2"}]


now here is the problem, in the webserver, the interpretation of the JSON generated from
test1x1
is that it has 3 entries, each 1 field. because MATLAB does not add
[]
in front and at the end of the generated JSON for a 1x1 struct.

the interpretation of the generated JSON from
test1x2
is correct and as expected: 2 entries, each 3 fields




Now, don't you think that the generated JSON of a 1x1 struct is wrong?

Answer

There is indeed a little ambiguity here: Matlab does not have the concept of a "one element array", Matlab treat such entities as scalars. Thus, you want to convert [struct('a','a','b','b','c','c')] (a list with single struct element) to json, but what matlab sees is struct('a','a','b','b','c','c') (a scalar struct element).
I suppose you can workaround it by forcing scalars to be items in a cell array: {struct('a','a','b','b','c','c')}.