我最近开始研究一个向服务器发出请求并获取json响应的应用程序。
“东西”运作得非常漂亮,直到我不得不在列表中实现新内容,现在我很难解决它。
非常感谢任何帮助:
class RemoteConfig
{
// names and type must match what we get from the remote
String[] username;
ArrayList<accDetails> in_groups;
String[] in_groups_sorted;
class accDetails
{
int group_id;
String group_label;
Boolean _is_system;
}
这只是课程开始的一部分,这里是json响应的样子:
{
"username":[
"mike"
],
"in_groups":[
{
"group_id":2,
"group_label":"All users",
"_is_system":true
},
{
"group_id":4372,
"group_label":"Privileged User",
"_is_system":false
},
{
"group_id":4979,
"group_label":"Supervisor",
"_is_system":false
}
]
}
我现在遇到的问题是,如果_is_system值为false,我不知道如何拆分in_groups数组列表并进入String [] in_groups_sorted Group_label的值。
非常感谢任何帮助。
谢谢你, 麦克
在检查答案后,最清洁,最简单的是阿贝提供的答案:
public String[] groupSettings()
{
String[] levels = new String[] {};
if (remoteConfig != null && remoteConfig.in_groups != null){
for (accDetails ad: remoteConfig.in_groups)
{
if (!ad._is_system) {
levels = ArrayUtils.addAll(levels, ad.group_label); ;
}
}
}
return levels;
}
答案 0 :(得分:1)
如果您不想改变解析JSON的方式,可以随时执行此操作:
让accDetails实现Comparable,然后使用传递in_groups的Collections.sort。
如果你真的想要String [],你总是可以遍历in_groups,添加到in_groups_sorted然后使用Arrays.sort
答案 1 :(得分:1)
从您的问题来看,我认为JSON已经被解析并存储在in_groups
类的RemoteConfig
字段中。您只需要过滤填充in_group_sorted
字段所需的信息。
将以下内容添加到RemoteConfig
类:
public initGroupSorted() {
// Temporary list, since we don't know the size once filtered
List<String> labels = new ArrayList<>();
for (accDetails ad : in_groups) {
if (ad._is_system) {
groups.add(ad.group_label);
}
}
in_group_sorted = labels.toArray(new String[labels.size()]);
}
答案 2 :(得分:0)
public void createObjects(String rawJSON) {
try {
JSONObject object = new JSONObject(rawJSON);
JSONArray username = object.getJSONArray("username");
JSONArray inGroups = object.getJSONArray("in_groups");
RemoteConfig config = new RemoteConfig();
config.in_groups = new ArrayList<>();
config.username = username.getString(0);
for (int i = 0; i < inGroups.length(); i++) {
JSONObject group = inGroups.getJSONObject(i);
if (!group.getBoolean("_is_system")) {
accDetails details = new accDetails();
details.group_id = group.getInt("group_id");
details.group_label = group.getString("group_label");
details._is_system = false;
config.in_groups.add(details);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
答案 3 :(得分:0)
以下是使用Stream's filter
,sorted
和map
方法的Java 8解决方案:
//ArrayList<accDetails> in_groups is already populated
Stream<accDetails> tempStream= in_groups.stream().filter(p -> p._is_system == false);
tempStream= tempStream.sorted((accDetails o1, accDetails o2) -> o1.group_label.compareTo(o2.group_label));
String[] in_groups_sorted = tempStream.map(s -> s.group_label).toArray(String[]::new);
将可见度调用分开,但它们可以是一个单一的内容:
String[] in_groups_sorted = in_groups.stream().filter(p -> p._is_system == false).sorted((accDetails o1, accDetails o2) -> o1.group_label.compareTo(o2.group_label)).map(s -> s.group_label).toArray(String[]::new);