恢复在其中数据被放入一个JSONObject顺序 [英] Restore the order in which data is put into a JSONObject

查看:281
本文介绍了恢复在其中数据被放入一个JSONObject顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想有JSON,因为它是插在这个code,但它的工作原理不同的东西!我首先要客户ID 然后名称但这JSON给名称,然后再客户ID 。我插入了JSON作为我想要的,但为什么它给了不同的结果,请帮助我..

  JSONObject的JSON =新的JSONObject();    尝试{
        json.put(客户ID,069C21F1-EE87-4FB4-A129-478AEAA454FF);
        json.put(姓名,名_+(int)的的Math.random()* 1000);
}赶上(JSONException E){
        // TODO自动生成catch块
        e.printStackTrace();
    }


解决方案

这是一个JSONObject的预期行为。通过它的定义,它说:

的对象作为一个无序的名称/值对

但是如果你希望它是命令做到这一点:

  1。 prepare与元素的LinkedHashMap的对象2.将其转换为的JSONObject

示例:

 地图的obj =新LinkedHashMap的();
obj.put(一,字符串1);
obj.put(b的,新的整数(1));
obj.put(C,新的布尔值(true));
obj.put(D,String2的);
JSONObject的JSON =新的JSONObject(OBJ);

编辑:

下载这个库:

<一个href=\"https://github.com/douglascrockford/JSON-java\">https://github.com/douglascrockford/JSON-java

保存在您的项目在一个新的包中的所有文件

而不是使用 org.json.JSONObject 使用 your.package.JSONObject 您从下载库补充说。

现在打开 JSONObject.java 文件并更改的HashMap() LinkedHashMap的()在构造函数中

 公开的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 have inserted the json as i want but why it gives different result please help me..

    JSONObject json = new JSONObject();

    try {
        json.put("CustomerID", "069C21F1-EE87-4FB4-A129-478AEAA454FF");
        json.put("Name", "Name_" + (int) Math.random() * 1000);
} catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

解决方案

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 LinkedHashMap object with elements

2. convert it to JSONObject

Example:

Map obj = new LinkedHashMap();
obj.put("a", "String1");
obj.put("b", new Integer(1));
obj.put("c", new Boolean(true));
obj.put("d", "String2");
JSONObject json = new JSONObject(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

public JSONObject(Map map)

这篇关于恢复在其中数据被放入一个JSONObject顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆