如何从java中的字符串json中删除键? [英] How to drop keys from string json in java?
本文介绍了如何从java中的字符串json中删除键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像这样的json字符串:
I have a json string like this:
{"a":"vala", "b":"valb", "c":"valc"}
我想将上面的字符串转换为JSONObject所以我可以这样做:
I want to convert the above string to a JSONObject so that I can do something like:
testObject.remove("b");
testObject.remove("c");
这样我就可以轻松打印出json字符串:
So that I can easily print out the json string of:
{"a":"vala"}
对我来说,最简单的方法是什么?
What is the simplest way for me to do this?
推荐答案
org-json-java 可以做你想要的事情
import org.json.JSONException;
import org.json.JSONObject;
public class JsonTest {
public static void main(String[] args) {
try {
JSONObject testObject = new JSONObject("{\"a\":\"vala\", \"b\":\"valb\", \"c\":\"valc\"}");
testObject.remove("b");
testObject.remove("c");
System.out.println(testObject.toString()); // This prints out the json string
} catch (JSONException e) {
e.printStackTrace();
}
}
}
执行结果是
{"a":"vala"}
确保您已从此处在您运行上述代码之前。
Make sure you've downloaded and imported org.json-YYYYMMDD.jar from here before you run the above code.
这篇关于如何从java中的字符串json中删除键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文