java - 使用 JSON 中的值填充数组很棘手

标签 java json

在开始之前,这是我的 JSON:(结构是刚性的,无法更改)

[
  {"_id":{"country":"au", "industry":"foo"}, "value":{"count":2}},
  {"_id":{"country":"au", "industry":"bar"}, "value":{"count":1}},
  {"_id":{"country":"be", "industry":"baz"}, "value":{"count":2}},
  ..
]

我不能有重复的国家/地区名称和行业名称。我有一个数组,要填充值

数组[au][foo] = 2

数组[au][bar] = 1

数组[be][baz] = 2

JSON 中的值未排序,并且所有国家/地区可能不具有相同的行业。

我该如何去做呢?这是我当前的代码:

for (int i = 0; i < jsonArray.size(); i++) {
        JSONObject jsonValue = jsonArray.get(i).isObject();

        JSONObject _id = jsonValue.get("_id").isObject();
        JSONObject value = jsonValue.get("value").isObject();

        String country = _id.get("country").isString().toString();
        setCountry.add(country);

        String industry = _id.get("industry").isString().toString();
        setIndustry.add(industry);

        int count = Integer.parseInt(value.get("count").isNumber()
                .toString());

    }

我正在将国家/地区和行业添加到集合中,以删除重复项。这就是导致计数问题的原因。我不在乎它是否优雅,黑客工作也可以。

谢谢。

最佳答案

我认为您可以使用枚举来解决您的问题。在这样的枚举中定义所有已知的国家/地区名称和行业。

public enum Country {
au,
be;
int Int=this.ordinal();//just a short name for ordinal
}

public enum Industry {
foo,
bar,
baz;
int Int=this.ordinal();
}

现在定义一个二维 int 数组,您可以使用枚举设置值,如下所示:

int[][] value=new int[Country.values().length][Industry.values().length];
value[Country.au.Int][Industry.bar.Int]=2;
//Read from JSON
value[Country.valueOf("au").Int][Industry.valueOf("bar").Int]=2;

如果您使用枚举,则可以将此代码添加到当前 for 循环的末尾:

value[Country.valueOf(country).Int][Industry.valueOf(industry).Int]=count;

另一种选择是避免使用数组并使用 Map 来代替:

Map<Country,Map<Industry,Integer>> m=new HashMap<Country,Map<Industry,Integer>>();

或者简单地不使用枚举:

Map<String,Map<String,Integer>> m=new HashMap<String,Map<String,Integer>>();

map 的问题在于,从其中添加和检索值有点棘手,但您可以编写通用方法来完成这项工作。

更新:

向内部映射添加值:

String[][] countryAndIndustry= {{"au","foo"},{"au","bar"},{"be","baz"}};
Integer[] count= {2,1,2};
HashMap<String,HashMap<String,Integer>> hm=new HashMap<String,    HashMap<String,Integer>>();
for(int i=0;i<count.length;i++)
{
    HashMap<String,Integer> innerMap=hm.get(countryAndIndustry[i][0]);
    if(innerMap==null)
    {
        innerMap=new HashMap<String, Integer>();
        hm.put(countryAndIndustry[i][0],innerMap);
    }
    innerMap.put(countryAndIndustry[i][1],count[i]);
}

关于java - 使用 JSON 中的值填充数组很棘手,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3904209/

相关文章:

java - 奇怪的 Java 类路径/类加载器行为

java - 为什么 java 应用程序在 Docker 容器中启动而不在暴露的端口上可用?

java - 我怎样才能让这个开关只选择 3 个选项之一?

java - Java Regex 中的声明差异?

java - 如何将 2d 阵列旋转小于 90°,以获得最佳近似值?

json - 使用 jq 展平/规范化 json 对象数组

javascript - 如何在javascript中读取以字符串 "2012-12-13"为键的json?

python - 使用 python 从 json 文件读取

javascript - 如何在键值过滤后从 JSON 追加

ajax - django:使用 json 对象测试基于 POST 的 View