writer.WriteBeginArray creates an exception

Nov 23, 2010 at 10:58 AM

Hi, I am a newbee in trying Json. I try to build a Json string like

{"id":1,"method":"slim.request","params":[ "-", ["player", "count","?" ]]}

I tried to do this wiht the follwing code, but it creates an exception. It looks like it does not allow to have an Array  ("[")  opener after "params:"

         writer.WriteObjectBegin();
            writer.WriteMember("id", 1);
            writer.WriteMember("method", "slim.request");
            writer.WriteMember("params"); 
            writer.WriteArrayBegin();
            writer.WriteMember("-");
            writer.WriteArrayBegin();
            writer.WriteMember("player");
            writer.WriteMember("count");
            writer.WriteMember("?");
            writer.WriteArrayEnd();
            writer.WriteArrayEnd();
        
            writer.WriteObjectEnd();

Any suggestions how to realize the above JSON string?

thanks

Gerald


 

Nov 23, 2010 at 9:27 PM
Edited Nov 23, 2010 at 9:33 PM

Hello Gerald,

You should change your code to following:

<code>

            writer.WriteObjectBegin();

            writer.WriteMember("id", 1);
            writer.WriteMember("method", "slim.request");
            writer.WriteMember("params");

            writer.WriteArrayBegin();
            writer.WriteValue("-");
            writer.WriteArrayBegin();
            writer.WriteValue("player");
            writer.WriteValue("count");
            writer.WriteValue("?");
            writer.WriteArrayEnd();
            writer.WriteArrayEnd();
       
            writer.WriteObjectEnd();
</code>

Hope this helps ;)

Some additional explanation:
The 'WriteMember' functions are supposed to be used inside object definition, where you specify <key> and <value>. The 'WriteValue' are to be used inside arrays, where you serialize data one by one.
'WriteMember' without second parameter is ment to be followed by another object (or array as in your case) definition for JSON like: { "a": { "internal": 1} }

<code>

 writer.WriteObjectBegin();
 writer.WriteMember("a");
 writer.WriteObjectBegin();
 writer.WriteMember("internal", 1);
 writer.WriteObjectEnd();
 writer.WriteObjectEnd();

</code>

If you have more data structures to convert to JSON I would also suggest using JSonMemberAttribute. Please take a look on unit test project for recipes, how to utilize it.

Cheers,
 Paweł