Reputation: 31
I'm trying to deserialize a JSON string into an object. I am using the System.JSON library within Xamarin and this is what I have so far:
ServerConnection.Receive (bb);
data = Encoding.ASCII.GetString (bb);
try{
MemoryStream stream = new MemoryStream(bb);
JsonValue jsonCounters = JsonObject.Load(stream);
}
catch(Exception error){
Console.WriteLine ("ERROR: " + error.Message);
}
The problem I am having is that jsonCounters is always null. I understand that JSON.NET is a better library, but using it would require upgrading my account, and that's something I'm not really ready to do just yet.
EDIT:
I followed the link supplied by JamesMontemagno. I then wrote the following into my application:
ServerConnection.Receive (bb);
data = Encoding.ASCII.GetString (bb);
try{
JsonValue value = JsonValue.Parse(data);
JsonObject jsonCounters = value as JsonObject;
}
catch(Exception error){
Console.WriteLine ("ERROR: " + error.Message);
}
The only problem is that when I create the byte array that I receive on I do:
byte[] bb = new byte[1024]
and the issue is then when I receive and try to parse the JSON it seems that the difference between the JSON length and the length of the byte array isn't lost, it's just converted to white space at the end of the JSON, which causes JsonValue.Parse to fail with ERROR: extra characters in JSON input. At line 1, column 642. I tried data = data.Trim(), but that did a whole lot of nothing.
Upvotes: 0
Views: 207
Reputation: 31
JamesMontemagno was right with his link. It showed me the correct usage of JsonObject. After I was able to get the Json to atleast atempt to parse I needed to remove the trailing white space. I did that by using the following code to create a new byte array that would parse.
ServerConnection.Receive (rawRecieve);
int i = rawRecieve.Length - 1;
while (rawRecieve [i] == 0) {
--i;
}
byte[] cleanRecieve = new byte[i+1];
Array.Copy(rawRecieve, cleanRecieve, i+1);
I stole that bit of code from: Removing trailing nulls from byte array in C#
Upvotes: 0