2014-03-05 2 views
-2
{ 
    "city" : "THAYNE", 
    "loc" : [ 
      -111.011354, 
      42.933026 
    ], 
    "pop" : 505, 
    "state" : "WY", 
    "_id" : "83127" 
} 

이 json 구문을 가지고 있으며이를 Java 객체로 파싱하고 싶습니다. 우선, .json 파일의 모든 행을 저장하기 위해 String 배열을 만들었습니다. 결국 나는 정말로 모르지만, 어떻게해야합니까?Java 객체에 대한 JSON

+1

반대 부사장 그래서, 기본적인 질문을 게시하는 대신 검색하고 시도하는 것이 무엇입니까? – Smutje

답변

3
###Gson is easy to learn and implement, what we need to know are following two methods 

toJson() – Convert Java object to JSON format 
fromJson() – Convert JSON into Java object ### 

import java.io.BufferedReader; 
import java.io.FileReader; 
import java.io.IOException; 
import com.google.gson.Gson; 

public class GsonExample { 
    public static void main(String[] args) { 

    Gson gson = new Gson(); 

    try { 

     BufferedReader br = new BufferedReader(
      new FileReader("c:\\file.json")); 

     //convert the json string back to object 
     DataObject obj = gson.fromJson(br, DataObject.class); 

     System.out.println(obj); 

    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    } 
} 
0

은 내가 라이브러리를 사용하여 조언을 위해 크림,하지만 GSON을 사용하여 얻을 것이다 : https://code.google.com/p/google-gson/

JsonParser 객체를 생성하고 거기에서 이동합니다. 지금까지 가장 쉬운. 또한 문자열 배열에 입력이 필요하지 않으므로 전체 JSON이 포함 된 String을 하나 만듭니다. 이 시도 : 당신은 GSON을 사용할 수 있습니다

JsonParser parser = new JsonParser(); 
try 
{ 
    JsonElement json = parser.parse("your json string"); 
    JsonObject obj = json.getAsJsonObject(); 
    // Now you have the JSon object, get any element from it now. 
    JsonElement city = obj.get("city"); 
    return city.getAsString(); 
} 
catch (JsonSyntaxException e) { 
} 
catch (JsonParseException e) { 
} 
0

- 자바가 JSON 표현으로 개체 변환하는 데 사용 될 수있는 자바 라이브러리를이 외부에 엄청나게 많은 도구와 같은있다

관련 문제