1. Add this dependency to your project:
What does this mean? See How to Add a Dependency to a Java Project
2. Put the following JSON sample in your classpath:
3. Load the resource from the classpath and parse this JSON as follows:
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.3</version>
<scope>compile</scope>
</dependency>
What does this mean? See How to Add a Dependency to a Java Project
2. Put the following JSON sample in your classpath:
{'foo':'bar',
'coolness':2.0,
'altitude':39000,
'pilot':{'firstName':'Buzz',
'lastName':'Aldrin'},
'mission':'apollo 11'}
3. Load the resource from the classpath and parse this JSON as follows:
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 );
}
}
'프로그램 언어 > 자바' 카테고리의 다른 글
JVM Options (0) | 2013.04.15 |
---|---|
숫자를 한글자리수로 표현 (0) | 2013.02.25 |
Java 날짜 계산 함수 모음 (0) | 2011.11.03 |
Json String Json객체로 생성하는 예제 (0) | 2010.03.04 |
POI 엑셀 다운로드 (1) | 2010.02.26 |