tags:

views:

127

answers:

1

This is a weird issue. I understand JSON is supposed to be unordered and the implementation of java.lang.JSONObject specifically mentions that it is unordered.

However, it puzzles me because I would expect the way I call the put(); methods it should keep my order. Maybe that contradicts what I just said in the beginning though.

I am using JSON to communicate with a WCF web service which requires me to include a __type key to designate the type of complex object I am sending.

I urge you to try this:

    JSONObject object = new JSONObject();
    try {
     object.put("__type", "Value1");
     object.put("SecondKey", "Value2");
     object.put("ThirdKey", "Value3");
    }
    catch (JSONException e) {
     e.printStackTrace();
    }

The output in the log is: {"ThirdKey":"Value3","__type":"Value1","SecondKey":"Value2"}

Now, I understand the implementation uses a HashMap and so the order is not maintained. But when calling a WCF service the key __type IS REQUIRED to be first for the deserialization to occur on the service. How can I achieve this? For sometime, I have been using plain Strings to send to the webservice which works fine. However, this is not acceptable as it is ugly and hard to maintain.

Please advice, either from the Java side or WCF side how I can tackle this problem.

Thanks!

A: 

However, it puzzles me because I would expect the way I call the put(); methods it should keep my order. Maybe that contradicts what I just said in the beginning though.

Yes it does.

But when calling a WCF service the key __type IS REQUIRED to be first for the deserialization to occur on the service.

If that is really true, it is (IMO) either a bug in the service implementation or (if the deserialization mechanism is generic to WCF) in WCF. In the former case, complain to the service implementor that the service is buggy. In the latter case, you could try complaining to Microsoft about breaking standards (yet again) ... but you'd be wasting your breath.

The correct place to fix this would be in the code on the WCF side that is doing the deserialization. But in practice, you may need to switch to a different Java JSON library that serializes in a way that makes WCF happy. Or maybe you could just hack the JSON library that you are currently using ...

Stephen C
If the __type is not first in the JSON object I receive a "Cannot create an abstract class" error from the service.thanks for your reply!
dnkoutso
@dnkoutso - in that case, either the service or the WCF infrastructure is broken, in my opinion; see the rest of my answer.
Stephen C
Thanks for the comment, we are in the process of fixing this on the server side...
dnkoutso