Java에서 JSON 개체 구문 분석 [중복]
이 질문에 이미 답변이 있습니다.
- Java 31 답변 에서 JSON을 구문 분석하는 방법
다음과 같이 JSON 개체가 있습니다.
member = "{interests : [{interestKey:Dogs}, {interestKey:Cats}]}";
Java에서 위의 json 객체를 구문 분석하고 값을 arraylist에 저장하고 싶습니다.
나는 이것을 달성 할 수있는 코드를 찾고있다.
목록에 interestKeys를 저장하고 싶다고 가정합니다.
은 Using 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"));
}
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));
}
}
}
}}
다른 답변으로 @Code에 감사드립니다. 귀하의 코드 덕분에 모든 JSON 파일을 읽을 수 있습니다. 이제 모든 요소를 레벨별로 정리하려고합니다.
URL에서 JSON을 읽는 Android로 작업하고 있었는데 변경해야 할 유일한 것은 라인이었습니다.
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);
}
}
}
}
1.) 적절한 유형의 배열 목록을 만듭니다.이 경우에는 String
2.) Create a JSONObject
while passing your string to JSONObject
constructor as input
- As
JSONObject
notation is represented by braces i.e{}
- Where as
JSONArray
notation is represented by square brackets i.e[]
3.) Retrieve JSONArray
from JSONObject
(created at 2nd step) using "interests"
as index.
4.) Traverse JASONArray
using loops upto the length of array provided by length()
function
5.) Retrieve your JSONObjects
from JSONArray
using getJSONObject(index)
function
6.) Fetch the data from JSONObject
using index '"interestKey"'.
Note : JSON
parsing uses the escape sequence for special nested characters if the json response (usually from other JSON response APIs) contains quotes ("
) like this
`"{"key":"value"}"`
should be like this
`"{\"key\":\"value\"}"`
so you can use JSONParser
to achieve escaped sequence format for safety as
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(inputString);
Code :
JSONParser parser = new JSONParser();
String response = "{interests : [{interestKey:Dogs}, {interestKey:Cats}]}";
JSONObject jsonObj = (JSONObject) parser.parse(response);
or
JSONObject jsonObj = new JSONObject("{interests : [{interestKey:Dogs}, {interestKey:Cats}]}");
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"));
}
Note : Sometime you may see some exceptions when the values are not available in appropriate type or is there is no mapping key
so in those cases when you are not sure about the presence of value so use optString
, optInt
, optBoolean
etc which will simply return the default value if it is not present and even try to convert value to int if it is of string type and vice-versa so Simply No null or NumberFormat exceptions at all in case of missing key or value
Get an optional string associated with a key. It returns the defaultValue if there is no such key.
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
or To get empty string i.e ""
if no key found then simply use
String missingKeyValue = json_data.optString("status");
// will return "" if no key found where "" is an empty string
Further reference to study
There are many JSON libraries available in Java.
The most notorious ones are: Jackson, GSON, Genson, FastJson and org.json.
There are typically three things one should look at for choosing any library:
- Performance
- Ease of use (code is simple to write and legible) - that goes with features.
- For mobile apps: dependency/jar size
Specifically for JSON libraries (and any serialization/deserialization libs), databinding is also usually of interest as it removes the need of writing boiler-plate code to pack/unpack the data.
For 1, see this benchmark: https://github.com/fabienrenaud/java-json-benchmark I did using JMH which compares (jackson, gson, genson, fastjson, org.json, jsonp) performance of serializers and deserializers using stream and databind APIs. For 2, you can find numerous examples on the Internet. The benchmark above can also be used as a source of examples...
Quick takeaway of the benchmark: Jackson performs 5 to 6 times better than org.json and more than twice better than GSON.
For your particular example, the following code decodes your json with jackson:
public class MyObj {
private List<Interest> interests;
static final class Interest {
private String interestKey;
}
private static final ObjectMapper MAPPER = new ObjectMapper();
public static void main(String[] args) throws IOException {
MyObj o = JACKSON.readValue("{\"interests\": [{\"interestKey\": \"Dogs\"}, {\"interestKey\": \"Cats\" }]}", MyObj.class);
}
}
Let me know if you have any questions.
참고URL : https://stackoverflow.com/questions/5015844/parsing-json-object-in-java
'IT박스' 카테고리의 다른 글
TensorFlow에서 사전 학습 된 단어 임베딩 (word2vec 또는 Glove) 사용 (0) | 2020.09.14 |
---|---|
MSIL 방법에서 hidebysig의 목적은 무엇입니까? (0) | 2020.09.14 |
TypeError : p.easing [this.easing]은 함수가 아닙니다. (0) | 2020.09.14 |
여러 환경에 대한 requirements.txt를 사용자 지정하는 방법은 무엇입니까? (0) | 2020.09.14 |
Perl에서 "my"키워드를 어떻게 사용해야합니까? (0) | 2020.09.14 |