Sometimes when we operate data, a lot of data is in jsonarry format
like:
[{"name":"test data","id":1},{"name":"test data 2","id":2}]This format is very type of table data type. But we need to take the name with id as 1 so that we need to variable first. If you need to operate such a type multiple times, it will be very troublesome.
We can see from the data here that id is unique. Then we can find a way to convert it to jsonobject so that we can easily get the name according to the specified id.
public static JSONObject toJSONObject(JSONArray jsonArray, String key) { JSONObject jsonObject = new JSONObject(); for (int i = 0; i < jsonArray.size(); i++) { JSONObject temp = jsonArray.getJSONObject(i); String[] keyValues = StringUtil.StringToArray(key); if (keyValues != null) { for (String item : keyValues) { String[] k = item.split(":"); String[] keys = k[0].split("_"); String keyName = k[0]; if (keys.length == 2) { keyName = keys[0]; } String jsonKeyName = temp.getString(keyName); if (keys.length == 2) { jsonKeyName += "_" + keys[1]; } jsonObject.put(jsonKeyName, temp.getString(k[1])); } } } return jsonObject; }This method can be implemented simply, but it may not be the best way to implement it. We welcome valuable suggestions to it.
Here are the cases
Case 1:
Original data: [{"name":"test data","id":1},{"name":"test data 2","id":2}] Call method: toJSONObject(jsonArray, "id:name") Result: {"1":"test data","2":"test data 2"}Case 2: (This is only what we need to add to our own business)
Original data: [{"name":"test data","id":1},{"name":"test data 2","id":2}] Call method: toJSONObject(jsonArray, "id_test:name") Result: {"1_test":"test data","2_test":"test data 2"}Case Three:
Original data: [{"no":100,"name":"test data","id":1,"desc":"test description"},{"no":101,"name":"test data 2","id":2,"desc":"test description 2"}] Call method: toJSONObject(jsonArray, "id:name,no:desc") Result: {"1":"test data","100":"test description","2":"test data 2","101":"test description 2"}The above java converts jsonarray into jsonobject method that corresponds to key values is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.