gpt4 book ai didi

java - 在 JSON 转换为 CSV 期间保持 JSON 键的顺序

转载 作者:IT老高 更新时间:2023-10-28 11:48:56 25 4
gpt4 key购买 nike

我正在使用此处提供的 JSON 库 http://www.json.org/java/index.html要将 json 字符串转换为 CSV。但我遇到的问题是,转换后键的顺序丢失了。

这是转换代码:

    JSONObject jo = new JSONObject(someString);
JSONArray ja = jo.getJSONArray("items");
String s = CDL.toString(ja);
System.out.println(s);

这是“someString”的内容:

{
"items":
[
{
"WR":"qwe",
"QU":"asd",
"QA":"end",
"WO":"hasd",
"NO":"qwer"
},
]
}

这是结果:

WO,QU,WR,QA,NO
hasd,asd,qwe,end,qwer

虽然我希望保持键的顺序:

WR,QU,QA,WO,NO
qwe,asd,end,hasd,qwer

有什么方法可以让我使用这个库获得这个结果?如果没有,是否有任何其他库可以提供保持结果中键顺序的功能?

最佳答案

有(hacky)方法可以做到这一点......但你不应该这样做。

在 JSON 中,对象是这样定义的:

An object is an unordered set of name/value pairs.

http://json.org .

JSON 的大多数实现都不会努力保留对象的名称/值对的顺序,因为它(根据定义)并不重要。

如果你想保留顺序,你需要重新定义你的数据结构;例如

{
"items":
[
[
{"WR":"qwe"},
{"QU":"asd"},
{"QA":"end"},
{"WO":"hasd"},
{"NO":"qwer"}
],
]
}

或更简单地说:

{
"items":
[
{"WR":"qwe"},
{"QU":"asd"},
{"QA":"end"},
{"WO":"hasd"},
{"NO":"qwer"}
]
}

跟进

Thanks for the info, but I have no choice but to use JSON in my application and my application needs to keep the order of the keys regardless of the definition of JSON object... I am not allowed to change the format of the JSON file as well...

您需要与设计该文件结构的人进行一次艰苦的对话,并且不会让您更改它。这是/他们完全错了。你需要说服他们。

如果他们真的不会让你改变它:

  • 你应该坚持称它为 JSON ...'因为它不是。
  • 您应该指出,您将不得不专门编写/修改代码来处理这种“非 JSON”格式……除非您能找到一些保留顺序的 JSON 实现。如果他们是付费客户,请确保他们为您必须做的这些额外工作付费。
  • 您应该指出,如果“非 JSON”需要由其他工具使用,那将是有问题的。确实,这个问题会反复出现...

这种事情真的很糟糕。一方面,您的软件将违反旨在促进互操作性的完善/长期规范。另一方面,设计这种蹩脚(不是 JSON!)文件格式的傻瓜可能正在淘汰其他人的系统等,因为系统无法处理他们的废话。

更新

JSON RFC (RFC 7159) 的内容也值得一读。在这个问题上说。以下是部分摘录:

In the years since the publication of RFC 4627, JSON has found verywide use. This experience has revealed certain patterns, which,while allowed by its specifications, have caused interoperabilityproblems.

JavaScript Object Notation (JSON) is a text format for theserialization of structured data. ...

JSON can represent four primitive types (strings, numbers, booleans,and null) and two structured types (objects and arrays).

An object is an unordered collection of zero or more name/valuepairs, where a name is a string and a value is a string, number,boolean, null, object, or array.

JSON parsing libraries have been observed to differ as to whether ornot they make the ordering of object members visible to callingsoftware. Implementations whose behavior does not depend on memberordering will be interoperable in the sense that they will not beaffected by these differences.

关于java - 在 JSON 转换为 CSV 期间保持 JSON 键的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4515676/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com