Skip to content Skip to sidebar Skip to footer

Restore The Order In Which Data Is Put Into A Jsonobject

i want to have json as it is inserted in this code but it works something different! i first want CustomerID and then Name but this json gives the Name first and then CustomerID. i

Solution 1:

That is the expected behavior of a JSONObject. By its definition, it says:

An object as an unordered set of name/value pairs

however if you want it to be ordered do this:

1. prepare a LinkedHashMapobjectwith elements

2. convert it to JSONObject

Example:

Map obj = newLinkedHashMap();
obj.put("a", "String1");
obj.put("b", newInteger(1));
obj.put("c", newBoolean(true));
obj.put("d", "String2");
JSONObject json = newJSONObject(obj);

EDIT:

download this library:

https://github.com/douglascrockford/JSON-java

save all the files in a new package in your project

instead of using org.json.JSONObject use your.package.JSONObject which you added from the downloaded library.

now open JSONObject.java file and change HashMap() to LinkedHashMap() in the constructor

publicJSONObject(Map map)

Solution 2:

You can put that Name before CustomerID line to satisfy yourself, but that wont make a difference at all. Because the data from json is extracted in the form of key value pairs. Its independent of the order its placed in.

Solution 3:

You can use accumulative()

See android developpers refference

Solution 4:

A useful answer here

Gson if your friend. This will print the ordered map into an ordered JSON string.

I used the latest version of Gson (2.3.1), you can can download it via the following options at the bottom of this post.

import java.util.LinkedHashMap;
import java.util.Map;

import com.google.gson.Gson;

publicclassOrderedJson {
    publicstaticvoidmain(String[] args) {
        // Create a new ordered map.Map<String,String> myLinkedHashMap = newLinkedHashMap<String, String>();

        // Add items, in-order, to the map.
        myLinkedHashMap.put("1", "first");
        myLinkedHashMap.put("2", "second");
        myLinkedHashMap.put("3", "third");

        // Instantiate a new Gson instance.Gson gson = newGson();

        // Convert the ordered map into an ordered string.String json = gson.toJson(myLinkedHashMap, LinkedHashMap.class);

        // Print ordered string.System.out.println(json); // {"1":"first","2":"second","3":"third"}
    }
}

Dependency Options Maven

<dependency><groupId>com.google.code.gson</groupId><artifactId>gson</artifactId><version>2.3.1</version></dependency>

Gradle

compile'com.google.code.gson:gson:2.3.1'

Or you can visit Maven Central for more download options.

Post a Comment for "Restore The Order In Which Data Is Put Into A Jsonobject"