behzad behzad - 2 years ago 161
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
is a 1x1 struct with 3 fields

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

test1x2 =

1x2 struct array with fields:


>> test1x2(1)

ans =

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

>> test1x2(2)

ans =

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

now I want to sent
as JSON to my webserver

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

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


and now ,
will generate the following JSON:


now here is the problem, in the webserver, the interpretation of the JSON generated from
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
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 Source

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')}.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download