我有JSON对象如下:
member = "{interests : [{interestKey:Dogs}, {interestKey:Cats}]}";
Run Code Online (Sandbox Code Playgroud)
在Java中,我想解析上面的json对象并将值存储在arraylist中.
我正在寻找一些代码,通过它我可以实现这一点.
dog*_*ane 144
我假设您要将interestKeys存储在列表中.
使用org.json库:
JSONObject obj = new JSONObject("{interests : [{interestKey:Dogs}, {interestKey:Cats}]}");
List<String> list = new ArrayList<String>();
JSONArray array = obj.getJSONArray("interests");
for(int i = 0 ; i < array.length() ; i++){
list.add(array.getJSONObject(i).getString("interestKey"));
}
Run Code Online (Sandbox Code Playgroud)
小智 10
public class JsonParsing {
public static Properties properties = null;
public static JSONObject jsonObject = null;
static {
properties = new Properties();
}
public static void main(String[] args) {
try {
JSONParser jsonParser = new JSONParser();
File file = new File("src/main/java/read.json");
Object object = jsonParser.parse(new FileReader(file));
jsonObject = (JSONObject) object;
parseJson(jsonObject);
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void getArray(Object object2) throws ParseException {
JSONArray jsonArr = (JSONArray) object2;
for (int k = 0; k < jsonArr.size(); k++) {
if (jsonArr.get(k) instanceof JSONObject) {
parseJson((JSONObject) jsonArr.get(k));
} else {
System.out.println(jsonArr.get(k));
}
}
}
public static void parseJson(JSONObject jsonObject) throws ParseException {
Set<Object> set = jsonObject.keySet();
Iterator<Object> iterator = set.iterator();
while (iterator.hasNext()) {
Object obj = iterator.next();
if (jsonObject.get(obj) instanceof JSONArray) {
System.out.println(obj.toString());
getArray(jsonObject.get(obj));
} else {
if (jsonObject.get(obj) instanceof JSONObject) {
parseJson((JSONObject) jsonObject.get(obj));
} else {
System.out.println(obj.toString() + "\t"
+ jsonObject.get(obj));
}
}
}
}}
Run Code Online (Sandbox Code Playgroud)
小智 6
非常感谢@Code在另一个答案中。由于您的代码,我可以读取任何JSON文件。现在,我正在尝试按级别组织所有元素,以便可以使用它们!
我正在与Android一起从URL读取JSON,唯一需要更改的是行
Set<Object> set = jsonObject.keySet();
Iterator<Object> iterator = set.iterator();
对于
Iterator<?> iterator = jsonObject.keys();
我分享我的实现,以帮助某人:
public void parseJson(JSONObject jsonObject) throws ParseException, JSONException {
Iterator<?> iterator = jsonObject.keys();
while (iterator.hasNext()) {
String obj = iterator.next().toString();
if (jsonObject.get(obj) instanceof JSONArray) {
//Toast.makeText(MainActivity.this, "Objeto: JSONArray", Toast.LENGTH_SHORT).show();
//System.out.println(obj.toString());
TextView txtView = new TextView(this);
txtView.setText(obj.toString());
layoutIzq.addView(txtView);
getArray(jsonObject.get(obj));
} else {
if (jsonObject.get(obj) instanceof JSONObject) {
//Toast.makeText(MainActivity.this, "Objeto: JSONObject", Toast.LENGTH_SHORT).show();
parseJson((JSONObject) jsonObject.get(obj));
} else {
//Toast.makeText(MainActivity.this, "Objeto: Value", Toast.LENGTH_SHORT).show();
//System.out.println(obj.toString() + "\t"+ jsonObject.get(obj));
TextView txtView = new TextView(this);
txtView.setText(obj.toString() + "\t"+ jsonObject.get(obj));
layoutIzq.addView(txtView);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
1.)创建适当类型的arraylist,在这种情况下,即 String
2.)创建JSONObject一会儿将字符串传递给JSONObject构造函数作为输入
JSONObject符号由括号表示即{}JSONArray符号用方括号表示,即[] 3.)使用作为索引JSONArray从JSONObject(在第二步创建)检索"interests"。
4.)JASONArray使用循环遍历length()函数提供的数组长度
5)检索您JSONObjects从JSONArray使用getJSONObject(index)功能
6.)通过JSONObject使用索引““ interestKey”' 获取数据。
注意: JSON如果json响应(通常来自其他JSON响应API)包含这样的引号("),则解析会将特殊的嵌套字符用于转义序列
`"{"key":"value"}"`
Run Code Online (Sandbox Code Playgroud)
应该是这样的
`"{\"key\":\"value\"}"`
Run Code Online (Sandbox Code Playgroud)
因此您可以使用JSONParser来实现转义序列格式的安全性
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(inputString);
Run Code Online (Sandbox Code Playgroud)
代码:
JSONParser parser = new JSONParser();
String response = "{interests : [{interestKey:Dogs}, {interestKey:Cats}]}";
JSONObject jsonObj = (JSONObject) parser.parse(response);
Run Code Online (Sandbox Code Playgroud)
要么
JSONObject jsonObj = new JSONObject("{interests : [{interestKey:Dogs}, {interestKey:Cats}]}");
Run Code Online (Sandbox Code Playgroud)
List<String> interestList = new ArrayList<String>();
JSONArray jsonArray = jsonObj.getJSONArray("interests");
for(int i = 0 ; i < jsonArray.length() ; i++){
interestList.add(jsonArray.getJSONObject(i).optString("interestKey"));
}
Run Code Online (Sandbox Code Playgroud)
注: 有时你可能会看到一些例外情况时,values are not available in appropriate type or is there is no mapping key在这些情况下,所以当你不能确定的价值存在这样使用optString,optInt,optBoolean等,这将直接返回默认值,如果它不存在,甚至尝试转换值INT如果它是字符串类型,反之亦然,因此如果缺少键或值,则根本不存在null或NumberFormat异常
获取与键关联的可选字符串。如果没有这样的键,它将返回defaultValue。
Run Code Online (Sandbox Code Playgroud)public String optString(String key, String defaultValue) {
String missingKeyValue = json_data.optString("status","N/A");
// note there is no such key as "status" in response
// will return "N/A" if no key found
Run Code Online (Sandbox Code Playgroud)
或要获取空字符串,即""如果找不到键,则只需使用
String missingKeyValue = json_data.optString("status");
// will return "" if no key found where "" is an empty string
Run Code Online (Sandbox Code Playgroud)
进一步参考研究