我使用名为JSONObject
的JSON库(如果需要,我不介意切换)。
我知道如何迭代JSONArrays
,但是当我从Facebook解析JSON数据时,我没有得到一个数组,只有一个JSONObject
,但我需要能够通过JSONObject[0]
访问一个项目它的索引,例如{
"http://http://url.com/": {
"id": "http://http://url.com//"
},
"http://url2.co/": {
"id": "http://url2.com//",
"shares": 16
}
,
"http://url3.com/": {
"id": "http://url3.com//",
"shares": 16
}
}
来获得第一个,我无法弄清楚如何去做。
{{1}}
答案 0 :(得分:546)
也许这会有所帮助:
jsonObject = new JSONObject(contents.trim());
Iterator<String> keys = jsonObject.keys();
while(keys.hasNext()) {
String key = keys.next();
if (jsonObject.get(key) instanceof JSONObject) {
// do something with jsonObject here
}
}
答案 1 :(得分:76)
对于我的情况,我发现迭代names()
效果很好
for(int i = 0; i<jobject.names().length(); i++){
Log.v(TAG, "key = " + jobject.names().getString(i) + " value = " + jobject.get(jobject.names().getString(i)));
}
答案 2 :(得分:42)
我会避免使用迭代器,因为它们可以在迭代期间添加/删除对象,也可以用于循环的干净代码。它将简单干净&amp;线路较少。
使用Java 8和Lamda [Update 4/2/2019]
import org.json.JSONObject;
public static void printJsonObject(JSONObject jsonObj) {
jsonObj.keySet().forEach(keyStr ->
{
Object keyvalue = jsonObj.get(keyStr);
System.out.println("key: "+ keyStr + " value: " + keyvalue);
//for nested objects iteration if required
//if (keyvalue instanceof JSONObject)
// printJsonObject((JSONObject)keyvalue);
});
}
使用旧方式[Update 4/2/2019]
import org.json.JSONObject;
public static void printJsonObject(JSONObject jsonObj) {
for (String keyStr : jsonObj.keySet()) {
Object keyvalue = jsonObj.get(keyStr);
//Print key and value
System.out.println("key: "+ keyStr + " value: " + keyvalue);
//for nested objects iteration if required
//if (keyvalue instanceof JSONObject)
// printJsonObject((JSONObject)keyvalue);
}
}
原始答案
import org.json.simple.JSONObject;
public static void printJsonObject(JSONObject jsonObj) {
for (Object key : jsonObj.keySet()) {
//based on you key types
String keyStr = (String)key;
Object keyvalue = jsonObj.get(keyStr);
//Print key and value
System.out.println("key: "+ keyStr + " value: " + keyvalue);
//for nested objects iteration if required
if (keyvalue instanceof JSONObject)
printJsonObject((JSONObject)keyvalue);
}
}
答案 3 :(得分:20)
不能相信在这个答案中没有比使用迭代器更简单和安全的解决方案......
JSONObject names ()
方法返回JSONObject键的JSONArray,因此您只需循环遍历它:
JSONObject object = new JSONObject ();
JSONArray keys = object.names ();
for (int i = 0; i < keys.length (); ++i) {
String key = keys.getString (i); // Here's your key
String value = object.getString (key); // Here's your value
}
答案 4 :(得分:16)
Iterator<JSONObject> iterator = jsonObject.values().iterator();
while (iterator.hasNext()) {
jsonChildObject = iterator.next();
// Do whatever you want with jsonChildObject
String id = (String) jsonChildObject.get("id");
}
答案 5 :(得分:7)
org.json.JSONObject现在有一个keySet()方法,它返回一个Set<String>
,并且很容易通过for-each循环。
for(String key : jsonObject.keySet())
答案 6 :(得分:6)
首先把它放在某个地方:
private <T> Iterable<T> iteratorToIterable(final Iterator<T> iterator) {
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return iterator;
}
};
}
或者,如果您可以访问Java8,只需:
private <T> Iterable<T> iteratorToIterable(Iterator<T> iterator) {
return () -> iterator;
}
然后简单地遍历对象的键和值:
for (String key : iteratorToIterable(object.keys())) {
JSONObject entry = object.getJSONObject(key);
// ...
答案 7 :(得分:4)
这里的大多数答案是针对平面JSON结构的,如果您有一个可能嵌套了JSONArrays或嵌套的JSONObjects的JSON,则会出现真正的复杂性。下面的代码片段满足了这种业务需求。它需要一个哈希图,以及带有嵌套JSONArrays和JSONObjects的分层JSON,并使用哈希图中的数据更新JSON
public void updateData(JSONObject fullResponse, HashMap<String, String> mapToUpdate) {
fullResponse.keySet().forEach(keyStr -> {
Object keyvalue = fullResponse.get(keyStr);
if (keyvalue instanceof JSONArray) {
updateData(((JSONArray) keyvalue).getJSONObject(0), mapToUpdate);
} else if (keyvalue instanceof JSONObject) {
updateData((JSONObject) keyvalue, mapToUpdate);
} else {
// System.out.println("key: " + keyStr + " value: " + keyvalue);
if (mapToUpdate.containsKey(keyStr)) {
fullResponse.put(keyStr, mapToUpdate.get(keyStr));
}
}
});
}
您必须在这里注意到,此方法的返回类型为空,但是将作为参考的第六个对象传递给调用方。
答案 8 :(得分:3)
我创建了一个小的递归函数,它遍历整个json对象并保存了密钥路径及其值。
// My stored keys and values from the json object
HashMap<String,String> myKeyValues = new HashMap<String,String>();
// Used for constructing the path to the key in the json object
Stack<String> key_path = new Stack<String>();
// Recursive function that goes through a json object and stores
// its key and values in the hashmap
private void loadJson(JSONObject json){
Iterator<?> json_keys = json.keys();
while( json_keys.hasNext() ){
String json_key = (String)json_keys.next();
try{
key_path.push(json_key);
loadJson(json.getJSONObject(json_key));
}catch (JSONException e){
// Build the path to the key
String key = "";
for(String sub_key: key_path){
key += sub_key+".";
}
key = key.substring(0,key.length()-1);
System.out.println(key+": "+json.getString(json_key));
key_path.pop();
myKeyValues.put(key, json.getString(json_key));
}
}
if(key_path.size() > 0){
key_path.pop();
}
}
答案 9 :(得分:2)
使用Java 8和lambda,更清洁:
"System.Data.SqlClient": "4.1.0"
答案 10 :(得分:1)
我曾经有一个json,它需要增加一个id,因为它们是0索引的并且破坏了Mysql自动增量。
因此,对于我编写此代码的每个对象 - 可能对某人有帮助:
Content-Type
用法:
public static void incrementValue(JSONObject obj, List<String> keysToIncrementValue) {
Set<String> keys = obj.keySet();
for (String key : keys) {
Object ob = obj.get(key);
if (keysToIncrementValue.contains(key)) {
obj.put(key, (Integer)obj.get(key) + 1);
}
if (ob instanceof JSONObject) {
incrementValue((JSONObject) ob, keysToIncrementValue);
}
else if (ob instanceof JSONArray) {
JSONArray arr = (JSONArray) ob;
for (int i=0; i < arr.length(); i++) {
Object arrObj = arr.get(0);
if (arrObj instanceof JSONObject) {
incrementValue((JSONObject) arrObj, keysToIncrementValue);
}
}
}
}
}
这可以转换为适用于JSONArray作为父对象
答案 11 :(得分:1)
我们使用了下面的代码集来迭代JSONObject
字段
Iterator iterator = jsonObject.entrySet().iterator();
while (iterator.hasNext()) {
Entry<String, JsonElement> entry = (Entry<String, JsonElement>) iterator.next();
processedJsonObject.add(entry.getKey(), entry.getValue());
}
答案 12 :(得分:1)
我做了一个小的方法来记录JsonObject字段,并得到一些刺痛。看看它是否有用。
/* CSS Document */
* {
margin: 0px;
padding: 0px;
border: 0px;
}
/*Body*/
body {
font-family:"Helvetica scary";
background-image: url("../images/background2.jpg");
background-size: cover;
position: relative;
}
.wrapper {
width: 100%;
}
/*Logo*/
.logo {
text-align: center;
clear: both;
opacity: 1;
background-color: rgba(255,255,255,0.6);
}
/*Topnav*/
.topnav {
width: 100%;
opacity: 1;
background-color: rgba(255, 255, 255, 0.6);
margin-bottom: 10px;
padding: 5px 0px 5px 0;
border-bottom: dotted #66A761;
border-top: dotted #66A761;
position: relative;
text-align:center;
}
.topnav ul {
display: inline;
text-align: center;
}
.topnav ul li {
display: inline-block;
margin: 0 47px;
padding: 0;
text-indent: 0;
position: relative;
cursor: pointer;
-webkit-transition: all 0.2s;
-moz-transition: all 0.2s;
-ms-transition: all 0.2s;
-o-transition: all 0.2s;
transition: all 0.2s;
}
.topnav a {
font-size: 20px;
font-weight: bold;
text-decoration: none;
}
.topnav a:link {
color: #9F257D;
}
.topnav a:hover {
color: #66A761;
}
.topnav input {
padding: 5px;
margin: 0 5px;
right: 20px;
border-radius: 25px;
border: 0;
background-color: rgba(0,0,0,.8);
width: 150px;
opacity: 0.7;
position: flex;
color: #FFF;
}
.topnav button {
background-color:#66A761;
border-radius: 25px;
padding: 5px;
color: #9FFF;
opacity: 0.9;
font-style:oblique;
}
/*submenu*/
.topnav ul li ul {
display: block;
position: absolute;
background-color: rgba(255, 255, 255, 0.6);
padding: 5px 5px;
z-index: 1;
}
.topnav ul li:hover ul li {
display: block;
z-index: 1;
}
.topnav li a:active {
color: #ffffff;
}
.topnav ul li ul li {
display: none;
margin: 0;
padding: 2px;
}
/*content*/
.container {
width: 930px;
margin: 70px auto 0;
display: flex;
flex-direction: row;
flex-wrap: wrap;
margin-bottom: 70px;
}
.container .box {
position: relative;
width: 300px;
height: 228px;
background: #555;
margin: 5px;
margin-bottom: 10px;
box-sizing: border-box;
display: inline-block;
}
.container .box .imgbox {
position: relative;
overflow: hidden;
}
.container .box .imgbox img {
transition: transform 2s;
}
.container .box:hover .imgbox img {
transform: scale(1.2);
}
.container .box .details {
position: absolute;
top: 10px;
left: 10px;
bottom: 10px;
right: 10px;
backgound: rgba(0,0,0,.8);
transform: scaleY(0);
transition: transform .5s;
}
.container .box:hover .details {
transform: scaleY(1);
}
.container .box .details .content {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
text-align: center;
padding: 15px;
color: #FFF;
}
.container .box .details .content h2{
margin: 0;
padding: 0;
font-size: 20px;
color: #FFF;
background-color: rgba(0,0,0,.8);
opacity: 0.7;
border-radius: 5px;
}
.container .box .details .content p{
margin: 0;
padding: 0;
font-size: 15px;
color: #FFF;
background-color: rgba(0,0,0,.8);
opacity: 0.7;
border-radius: 5px;
}
.container .box .details .content a {
margin: 0;
padding: 0;
font-size: 20px;
color: #FFF;
text-decoration: none;
}
/*Footer*/
.footer {
clear: both;
margin: 60px 0 0 0;
padding: 30px;
text-align: center;
color :#9F257D;
border-top: dotted #66A761;
border-bottom: dotted #66A761;
opacity: 0.9;
background-color: rgba(255,255,255,0.6);
}
.footer img {
padding: 0 5px;
}
/*Under Construction*/
@media only screen and (min-width: 768px) and (max-width: 991px) {
.wrapper {
width: 100%
}
/*topnav*/
.topnav {
flex-direction: column;
}
.topnav ul {
flex-direction: row;
margin-bottom: 1em;
}
}
@media only screen and (max-width: 767px) {
.wrapper {
width: 100%;
font-size: 15px;
}
/*topnav*/
.topnav {
flex-direction: column;
max-width: 100%;
align-content: center;
}
.topnav ul {
flex-direction: row;
margin-bottom: 1em;
}
.topnav li {
padding: 0;
font-size: 11px;
}
.topnav input {
}
/*Text Area*/
.main {
max-width:100%;
}
/*content*/
.container {
max-width: 100%;
}
}
@media only screen and (max-width: 500px) {
.banner {
visibility: hidden;
max-width: 300px;
}
}
答案 13 :(得分:0)
下面的代码对我来说很好。如果可以进行调整,请帮助我。这甚至可以从嵌套的JSON对象中获取所有键。
self.complexes = [somethingAA:[somethingBB:somethingCC]]
答案 14 :(得分:0)
更简单的方法是(仅在W3Schools上找到):
let data = {.....}; // JSON Object
for(let d in data){
console.log(d); // It gives you property name
console.log(data[d]); // And this gives you its value
}
这种方法在您处理嵌套对象之前都可以正常工作。
const iterateJSON = (jsonObject, output = {}) => {
for (let d in jsonObject) {
if (typeof jsonObject[d] === "string") {
output[d] = jsonObject[d];
}
if (typeof jsonObject[d] === "object") {
output[d] = iterateJSON(jsonObject[d]);
}
}
return output;
}
并使用这种方法
let output = iterateJSON(your_json_object);
答案 15 :(得分:-1)
这是解决该问题的另一个可行方法:
public void test (){
Map<String, String> keyValueStore = new HasMap<>();
Stack<String> keyPath = new Stack();
JSONObject json = new JSONObject("thisYourJsonObject");
keyValueStore = getAllXpathAndValueFromJsonObject(json, keyValueStore, keyPath);
for(Map.Entry<String, String> map : keyValueStore.entrySet()) {
System.out.println(map.getKey() + ":" + map.getValue());
}
}
public Map<String, String> getAllXpathAndValueFromJsonObject(JSONObject json, Map<String, String> keyValueStore, Stack<String> keyPath) {
Set<String> jsonKeys = json.keySet();
for (Object keyO : jsonKeys) {
String key = (String) keyO;
keyPath.push(key);
Object object = json.get(key);
if (object instanceof JSONObject) {
getAllXpathAndValueFromJsonObject((JSONObject) object, keyValueStore, keyPath);
}
if (object instanceof JSONArray) {
doJsonArray((JSONArray) object, keyPath, keyValueStore, json, key);
}
if (object instanceof String || object instanceof Boolean || object.equals(null)) {
String keyStr = "";
for (String keySub : keyPath) {
keyStr += keySub + ".";
}
keyStr = keyStr.substring(0, keyStr.length() - 1);
keyPath.pop();
keyValueStore.put(keyStr, json.get(key).toString());
}
}
if (keyPath.size() > 0) {
keyPath.pop();
}
return keyValueStore;
}
public void doJsonArray(JSONArray object, Stack<String> keyPath, Map<String, String> keyValueStore, JSONObject json,
String key) {
JSONArray arr = (JSONArray) object;
for (int i = 0; i < arr.length(); i++) {
keyPath.push(Integer.toString(i));
Object obj = arr.get(i);
if (obj instanceof JSONObject) {
getAllXpathAndValueFromJsonObject((JSONObject) obj, keyValueStore, keyPath);
}
if (obj instanceof JSONArray) {
doJsonArray((JSONArray) obj, keyPath, keyValueStore, json, key);
}
if (obj instanceof String || obj instanceof Boolean || obj.equals(null)) {
String keyStr = "";
for (String keySub : keyPath) {
keyStr += keySub + ".";
}
keyStr = keyStr.substring(0, keyStr.length() - 1);
keyPath.pop();
keyValueStore.put(keyStr , json.get(key).toString());
}
}
if (keyPath.size() > 0) {
keyPath.pop();
}
}