使用java访问JSON属性名
我正在研究一种解析JSON文件并收集其内容以供其他地方使用的方法。我目前有一个工作示例,如下所示:使用java访问JSON属性名,java,json,Java,Json,我正在研究一种解析JSON文件并收集其内容以供其他地方使用的方法。我目前有一个工作示例,如下所示: import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class testJSONParser {
public static void main(String[] args) throws Exception {
List<Map<String, String>> jsonArray = new ArrayList<Map<String, String>>();
BufferedReader br = new BufferedReader(new FileReader("json.txt"));
try {
String line = br.readLine();
while (line != null) {
JSONObject jsonObject = (JSONObject)new JSONParser().parse(line);
Map<String, String> currentLineMap = new HashMap<String, String>();
currentLineMap.put("country", jsonObject.get("country").toString());
currentLineMap.put("size", jsonObject.get("size").toString());
currentLineMap.put("capital", jsonObject.get("capital").toString());
jsonArray.add(currentLineMap);
line = br.readLine();
}
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
br.close();
};
}
}
}
我的问题是如何获取这段代码,并使put方法能够动态地分配给相应的映射。这就是我目前拥有的:
for (int i = 0; i < jsonObject.size(); i++) {
currentLineMap.put(jsonObject.???.toString(), jsonObject.get(i).toString());
}
for(int i=0;i
那个???部分是我被难倒的地方。获取当前JSON行的值非常容易。但如何获取属性值(在JSON字符串示例中以粗体突出显示)让我困惑。是否有一种方法可以调用我不熟悉的对象?一个不同的更好的方法来通过这一点?或者说,我从一开始就完全是逆向的吗?在JSON.org参考实现中,您可以这样做:
for (String key : JSONObject.getNames(jsonObject))
{
map.put(key, jsonObject.get(key));
}
在JSON simple中,您将执行以下操作:
for (Object keyObject : jsonObject.keySet())
{
String key = (String)keyObject;
map.put(key, (String)jsonObject.get(key));
}
这应该可以解决问题。getNames从哪里来?正如您在我发布的代码中看到的,它是JSONObject类的静态方法。您使用的是同一个库吗?当我在我的项目中使用这段代码时,我得到了“类型JSONObject的getNames(JSONObject)方法是未定义的”。请允许我编辑我的答案。不用担心,也许我对该库使用了错误的名称,如果需要,我会查看并更新。
for (Object keyObject : jsonObject.keySet())
{
String key = (String)keyObject;
map.put(key, (String)jsonObject.get(key));
}