json problem java
I have a something like this
String value={"name":"Michal","location":"unknown"}
I would like to get all elements using JSONOBJECT
Something like this doesn't work:
JSONObject json = (JSONObject)new JSONParser().parse(value);
System.out.prin开发者_如何学运维tln(json.get("name"))
I get this from server http://localhost:4567/resource.json when I do value.toString() i excatly get what I wrote above.
I have got code:
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);
You can try this method。
JSONObject json=JSONObject.fromObject(object)
If it's have some exceptions.Pls paste them.
Are you sure that you defined your string variable correct?
String name = "Michal";
String location = "unknown";
String value="{\"name\":\"" + name + "\", \"location\":\"" + unknown + "\"}"
I have solved this problem I think that the problem was with encoding now I use URLConnection and it works:
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;
}
}
精彩评论