2011-03-10 41 views
0

我有這樣的事情JSON問題在java

String value={"name":"Michal","location":"unknown"} 

我想使用的JSONObject

讓所有元素

像這樣的東西不起作用:

JSONObject json = (JSONObject)new JSONParser().parse(value);   
System.out.println(json.get("name")) 
+0

不工作怎麼樣?你有任何錯誤? – Thilo 2011-03-10 08:21:25

+0

請發佈您的stacktrace,除了字符串'值'是不正確的Java語法。 – 2011-03-10 08:22:18

+2

'String value = {「name」:「Michal」,「location」:「unknown」} - - 這不可能是正確的。 – 2011-03-10 08:23:15

回答

0

你可以試試這種方法。

JSONObject json=JSONObject.fromObject(object) 

如果有一些異常,請將其粘貼。

+0

當value.toString()我有確切的: – Michal 2011-03-10 08:53:29

+0

它不起作用:/ – Michal 2011-03-10 09:14:27

1

我從服務器得到這http://localhost:4567/resource.json 當我做value.toString()我興奮地得到我上面寫的東西。

我有代碼:

in = new BufferedInputStream(new URL(address).openStream()); 
// fout = new FileOutputStream(budaPath + destination); 

byte data[] = new byte[1024]; 
int count; 
while ((count = in.read(data, 0, 1024)) != -1) 
{ 
    System.out.println(" "+data); 
    //fout.write(data, 0, count); 
} 

String value = new String(data); 
System.out.println(value); 
0

你確定你定義你的字符串變量是否正確?

String name = "Michal"; 
String location = "unknown"; 
String value="{\"name\":\"" + name + "\", \"location\":\"" + unknown + "\"}" 
0

我已經解決了這個問題,我覺得現在的問題是與編碼,現在我用的URLConnection和它的作品:

public class Json { 
    public static JSONObject getJSON(String address) throws MalformedURLException, IOException, ParseException{ 

    URL url=new URL(address); 
    URLConnection connection=url.openConnection(); 
    connection.connect(); 
    Scanner in=new Scanner(connection.getInputStream()); 
    StringBuilder sb=new StringBuilder(); 
    while (in.hasNextLine()){ 
     sb.append(in.nextLine()); 
    } 
    String value=sb.toString(); 
    JSONObject json = (JSONObject)new JSONParser().parse(value); 

    return json; 

    } 
}