问题
I am having a lot of tourble with this. I am trying to work on an updater and i am using an api that returns this from a url.: JSON
[
{
"downloadUrl":"URL",
"fileName":"Name",
"gameVersion":"Version",
"name":"Name",
"projectId":ID,
"releaseType":"beta"
},
{
"downloadUrl":"URL",
"fileName":"Name",
"gameVersion":"Version",
"name":"Name",
"projectId":ID,
"releaseType":"beta"
}
]
How can i get The Data out of this JSON returned by the URL. I do not want to use and "3rd Party" Parsers. Thanks. Also, i was stuck on this part:
I know i need to loop though an array, but there is no main array, unless it is "". ? That is what confused me. How can i parse this JSON from a url?
I saw someone did it like this, but idk if that will owrk in my JSON? Parsing JSON Object in Java
回答1:
In this case, your data is an array of objects, which can be stored to a HashMap object. Therefore we will retrieve each object in your array and add them into each HashMap. The HashMap works by using using a key to insert a value, i.e. HashMap<key type,value type>
. To store a value with a key, you use HashMap.put(key,value)
for example, map.put("downloadUrl", "URL")
// Remove the spacings yourself before trying the code
JSONArray array = new JSONArray("[
{
"downloadUrl":"URL",
"fileName":"Name",
"gameVersion":"Version",
"name":"Name",
"projectId":ID,
"releaseType":"beta"
},
{
"downloadUrl":"URL",
"fileName":"Name",
"gameVersion":"Version",
"name":"Name",
"projectId":ID,
"releaseType":"beta"
}
]");
List<HashMap<String,String>> list = new ArrayList<HashMap<String,String>();
for(int i = 0 ; i < array.length() ; i++){
HashMap<String,String> ht = new HashMap<String,String>();
JSONObject o = json.getJSONObject(i);
map.put("downloadUrl",o.getString("downloadUrl");
map.put("fileName",o.getString("fileName");
map.put("gameVersion",o.getString("gameVersion");
map.put("name",o.getString("Name"));
map.put("projectId",o.getString("projectId");
map.put("releaseType",o.getString("releaseType");
list.add(map);
}
来源:https://stackoverflow.com/questions/19483891/parsing-json-in-java-with-org-json