Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jsoncpp stop making it write based on elements alphabetical order

Tags:

c++

json

jsoncpp

I am using Jsoncpp to write a Json::value to a string using the Json::FastWriter.

string s;
s.append("me?json=");
val["firstname"] = firstname;
val["lastname"] = lastname;
val["x"] = me->myPos.X;
val["y"] = me->myPos.Y;
val["z"] = me->myPos.Z;
val["lookx"] = me->myOri.X;
val["looky"] = me->myOri.Y;
val["lookz"] = me->myOri.Z;
url.append(writer.write(val));

The problem is they don't appear in the string as in the order that I added them to the Json::value val, they seem to be alphabetically sorted depending on the first letter in each element("firstname, lastname, lookx, looky, lookz,x",etc). How do you prevent this? I want it to be added in the order that I add it to the Json::value and NOT be sorted.

If this is not possible, how would one alter the source code to achieve it?

Thanks

like image 762
KaiserJohaan Avatar asked Sep 28 '11 11:09

KaiserJohaan


1 Answers

Most likely Jsoncpp uses a std::map to store the key/value pairs, and it will return you an alphabetically-ordered key/value pairs. I've not looked into the code of Jsoncpp, but you have two alternatives:

  1. Change the code to use internally a std::list or some other ordered container (vector, etc.). That may result in performance penalty.
  2. Store the order of the keys you want to output and produce the output yourself.

However, as you may know, the order of keys in JSON is not specified, so if you're relying on that fact, you should reconsider your application design.

like image 176
Diego Sevilla Avatar answered Oct 17 '22 21:10

Diego Sevilla