2012-09-27 3 views
1

Bing Search API를 사용하여 웹 검색 결과를 얻습니다. 상위 2 개의 문서를 얻었고 JSON은 아래에 나와 있습니다.json을 java로 구문 분석하는 방법

{"d": 
{"results": 
[{"__metadata": 
    {"uri":"https://api.datamarket.azure.com/Data.ashx/Bing/SearchWeb/v1/Web?Query=\u0027bill\u0027gates\u0027&$skip=0&$top=1","type":"WebResult"}, 
    "ID":"9bd0942f-fe5b-44fc-8343-ef85e5b93a7e", 
    "Title":"The Official Site of Bill Gates - The Gates Notes", 
    "Description":"In the space between business and goverment, even a small investment can make a big impact on the lives of those in need.", 
    "DisplayUrl":"www.thegatesnotes.com", 
    "Url":"http://www.thegatesnotes.com/"}, 

{"__metadata": 
    {"uri":"https://api.datamarket.azure.com/Data.ashx/Bing/SearchWeb/v1/Web?Query=\u0027bill\u0027gates\u0027&$skip=1&$top=1","type":"WebResult"}, 
    "ID":"fdf0d3b9-b29f-43ef-b5ba-6bb4b1b04458", 
    "Title":"Bill Gates - Wikipedia, the free encyclopedia", 
    "Description":"William Henry \"Bill\" Gates III (born October 28, 1955) is an American business magnate and philanthropist. Gates is the former chief executive and current chairman of ...", 
    "DisplayUrl":"en.wikipedia.org/wiki/Bill_Gates", 
    "Url":"http://en.wikipedia.org/wiki/Bill_Gates"}, 

], 
"__next":"https://api.datamarket.azure.com/Data.ashx/Bing/SearchWeb/v1/Web?Query=\u0027bill\u0027gates\u0027&$skip=10&$top=10" 
} 
} 

어떻게 Gson을 사용하여 Java로 구문 분석 할 수 있습니까? 이러한 링크에

+4

http://code.google.com/에서 문서를 읽기 당신을 도와줍니다 p/google-gson/ – Jesper

+1

정말 간단합니다. 노력을 보여 주시면 기꺼이 도와 드리겠습니다. – Nishant

+0

두 클래스 d와 메타 데이터를 구축하지만 fromJson()을 사용할 때 null이 발생합니다. 나는이 Json String의 데이터 구조를 모른다. –

답변

1
public class Metadata{ 
    public String uri; 
    public String Query; 
    public String ID; 
    public String Title; 
    public String Description; 
    public String DisplayUrl; 
    public String Url; 
} 

public class ResponseResults{ 
    public MetadataContainer[] results; 
    public String __next; 
} 


public class MetadataContainer{ 
    public Metadata __metadata; 
} 


public class ResponseData{ 
    public ResponseResults d; 
} 

String json; //Your json response 
ResponseData myD = new Gson().fromJson(json, ResponseData.class); 
+0

안녕하세요, 귀하의 데이터 구조를 사용하지만 myD null입니다. 구조물에 문제가 있습니까? –

+0

예 sory. 시험하지 않았어. 나는 대답을 편집 할 것이다 – Greensy

+0

예, "d"바깥에 컨테이너가있다! 고마워! –

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

public class GsonDemo { 
    public static void main(String[] args) { 
    Gson gson = new Gson(); 
    try { 
     String json = "" ; // your json string 
     //convert the json string to object 
     YourObject obj = gson.fromJson(json, YourObject.class); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    } 
} 
관련 문제