当我的json看起来像这样时,我发现从json对象执行键值有些困难:
{
"access_token":"ya29.UwD44cI4z8KTjCEAAAA1RHrx3vi2zkNnzKvR-lb6o8TtMFZnfuCK71yq59eq4YhdaFsGZcUe2hhUiW7MgHc",
"token_type":"Bearer",
"expires_in":3600,
"refresh_token":"1/qDxXmtxMOTTjhhaSsjfEdMe61Rw9l8I5oS-ct5xNc1o"
}
我该怎么做?
答案 0 :(得分:1)
那里已经有很多例子,但你去了HERE。
将此依赖项添加到项目中:
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.3</version>
<scope>compile</scope>
</dependency>
将以下JSON示例放在类路径中:
{'foo':'bar',
'coolness':2.0,
'altitude':39000,
'pilot':{'firstName':'Buzz',
'lastName':'Aldrin'},
'mission':'apollo 11'}
从类路径加载资源并按如下方式解析此JSON:
package com.discursive.answers;
import java.io.InputStream;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import org.apache.commons.io.IOUtils;
public class JsonParsing {
public static void main(String[] args) throws Exception {
InputStream is =
JsonParsing.class.getResourceAsStream( "sample-json.txt");
String jsonTxt = IOUtils.toString( is );
JSONObject json = (JSONObject) JSONSerializer.toJSON( jsonTxt );
double coolness = json.getDouble( "coolness" );
int altitude = json.getInt( "altitude" );
JSONObject pilot = json.getJSONObject("pilot");
String firstName = pilot.getString("firstName");
String lastName = pilot.getString("lastName");
System.out.println( "Coolness: " + coolness );
System.out.println( "Altitude: " + altitude );
System.out.println( "Pilot: " + lastName );
}
}
答案 1 :(得分:0)
package stackoverflow.q_25052046;
//Required imports
public class HandleJSON {
private static String jsonString = "[{ \"access_token\" : \"ya29.UwD44cI4z8KTjCEAAAA1RHrx3vi2zkNnzKvR-lb6o8TtMFZnfuCK71yq59eq4YhdaFsGZcUe2hhUiW7MgHc\", \"token_type\" : \"Bearer\", \"expires_in\" : 3600, \"refresh_token\" : \"1/qDxXmtxMOTTjhhaSsjfEdMe61Rw9l8I5oS-ct5xNc1o\"}]";
public static void main(String[] args) throws JSONException {
JSONArray jsonArray = new JSONArray(jsonString);
System.out.println("Converted object = " + jsonArray); //Outputting the result
System.out.println("..........................................");
for (int i = 0; i < jsonArray.length(); i++) { //Iterating over array
JSONObject jsonObject = jsonArray.getJSONObject(i);
System.out.println("access_token = " + jsonObject.getString("access_token"));
System.out.println("token_type = " + jsonObject.getString("token_type"));
System.out.println("expires_in = " + jsonObject.getString("expires_in"));
System.out.println("refresh_token = " + jsonObject.getString("refresh_token"));
}
}
}
//Output:
//Converted object = [{"expires_in":3600,"token_type":"Bearer","refresh_token":"1/qDxXmtxMOTTjhhaSsjfEdMe61Rw9l8I5oS-ct5xNc1o","access_token":"ya29.UwD44cI4z8KTjCEAAAA1RHrx3vi2zkNnzKvR-lb6o8TtMFZnfuCK71yq59eq4YhdaFsGZcUe2hhUiW7MgHc"}]
//..........................................
//access_token = ya29.UwD44cI4z8KTjCEAAAA1RHrx3vi2zkNnzKvR-lb6o8TtMFZnfuCK71yq59eq4YhdaFsGZcUe2hhUiW7MgHc
//token_type = Bearer
//expires_in = 3600
//refresh_token = 1/qDxXmtxMOTTjhhaSsjfEdMe61Rw9l8I5oS-ct5xNc1o