gpt4 book ai didi

java - 将值添加到 JSONArray 时如何保持值的顺序?

转载 作者:行者123 更新时间:2023-12-01 18:18:42 26 4
gpt4 key购买 nike

我需要从对象列表生成 JSON。为此,我使用以下代码,但有两个问题:

  1. 条目顺序发生变化
  2. 当我显示 JSON 时,它会在所有 " 之前添加 \

JSONObject jsonObj = new JSONObject();
for (Row row : rows) {
jsonObj.put(row.getCode(),row.getValue());

}
myJson.put(jsonObj.toString());
System.err.println("myJson:" + myJson.toString());

输出

myJson:["{\"1234445\":\"Jack"}"]

感谢 Sotirios Delimanolis ,从 jsonObj 中删除 .toString() 后,第一个问题已经解决。

最佳答案

我们在项目中使用比较器来获取 Json 数组的顺序。我发布的内容与您只需根据您的元素使用数组即可。

GetSortedList 是 array 接受数组并返回排序后的列表的方法。@

               List<JsonElement> lJaArray = null;
lJaArray = getSortedList( lJaArrayUnsorted ); // theJson array you want to sort.

public static List getSortedList( JsonArray array ) throws JSONException { List list = new ArrayList(); for( int i = 0; i < array.size(); i++ ) { list.add( array.get( i ) ); } Collections.sort( list, new Comparator() {

@Override
public int compare( JsonElement o1,
JsonElement o2 )
{

if( Integer.parseInt( o1.getAsJsonObject()
.get( "com.tangoe.matrix.catalog.CatalogFeatureDetail" )
.getAsJsonObject()
.get( "order" )
.toString()
.replace( "\"",
"" ) ) > Integer.parseInt( o2.getAsJsonObject()
.get( "com.tangoe.matrix.catalog.CatalogFeatureDetail" )
.getAsJsonObject()
.get( "order" )
.toString()
.replace( "\"",
"" ) ) )
{
return 1;
}
else if( Integer.parseInt( o1.getAsJsonObject()
.get( "com.tangoe.matrix.catalog.CatalogFeatureDetail" )
.getAsJsonObject()
.get( "order" )
.toString()
.replace( "\"",
"" ) ) < Integer.parseInt( o2.getAsJsonObject()
.get( "com.tangoe.matrix.catalog.CatalogFeatureDetail" )
.getAsJsonObject()
.get( "order" )
.toString()
.replace( "\"",
"" ) ) )
{
return -1;
}
else
{
return 0;
}

}
} );

return list;

}

我已经发布了我的元素,只需替换其中的数组元素即可。

关于java - 将值添加到 JSONArray 时如何保持值的顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28184466/

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