I'm trying to parse Java Object to get data from a URL. I'm using getJSONObject and getString methods from org.json.JSONObject library but this it's not working. I'm doing something like...
JSONObject jsonCoord = json.getJSONObject("results")
.getJSONObject("geometry")
.getJSONObject("location");
coordinates[0] = jsonCoord.getString("lat");
coordinates[1] = jsonCoord.getString("lng");
JSON document I want to parse (Part 1)
JSON document I want to parse (Part 2)
How can I get "lat" and "lng" which is inside of "geometry"?
Here it is:
public static void main(String args[]) throws Exception {
String content = new String(Files.readAllBytes(Paths.get("test.json")), "UTF-8");
JSONObject json = new JSONObject(content);
JSONArray results = json.getJSONArray("results");
JSONObject result = (JSONObject) results.get(0); //or iterate if you need for each
JSONObject jsonCoord = result.getJSONObject("geometry").getJSONObject("location");
System.out.println(jsonCoord);
String[] coordinates = new String[2];
coordinates [0] = jsonCoord.getString("lat");
coordinates[1] = jsonCoord.getString("lng");
System.out.println(Arrays.asList(coordinates));
}
Related
I am trying to get the values from a JSON response. I got everything to work, except extracting an array from the following string:
{"o":"1.18988","h":"1.18993","l":"1.18963","c":"1.18993"}
I know GSON is trying to parse it because I get this error:
Exception in thread "main" java.lang.IllegalStateException: Not a JSON Array: {"o":"1.18988","h":"1.18993","l":"1.18963","c":"1.18993"}
I am using the following code to attempt to parse it:
final JsonElement midElement = obj.get("mid");
final JsonArray midArray = midElement.getAsJsonArray();
for(Object rate : midArray){
final JsonObject rateObj = (JsonObject)rate;
final JsonElement openElement = rateObj.get("o");
open = openElement.getAsFloat();
final JsonElement highElement = rateObj.get("h");
high = highElement.getAsFloat();
final JsonElement lowElement = rateObj.get("l");
low = lowElement.getAsFloat();
final JsonElement closeElement = rateObj.get("c");
close = closeElement.getAsFloat();
}
First of all it doesn't look like a valid JSON array. It should look like this
[{"o":"1.18988","h":"1.18993","l":"1.18963","c":"1.18993"}]
Try this following code to parse it in JSON format.
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray jsonArray = jsonObject.getJSONArray("mid");
for (int i = 0; i < jsonArray.length(); i++) {
jsonArray.getJSONObject(i).getString("o");
}
Then convert it your preferred data form.
String theString="{
"0": "{\"birthPlace\":\"city1 \",\"gender\":\"m\",\"city\":\"city1 \",\"dob\":\"-\",\"homeNo\":\"city1 \",\"nic\":\"321654987\",\"fullName\":\"amith\",\"lang\":\"en\"}",
"1": "{\"birthPlace\":\"city2 \",\"gender\":\"m\",\"city2\":\"city2 \",\"dob\":\"-\",\"homeNo\":\"city2 \",\"nic\":\"22336655\",\"fullName\":\"sumith\",\"lang\":\"en\"}",
"2": "{\"birthPlace\":\"city3 \",\"gender\":\"m\",\"city2\":\"city3 \",\"dob\":\"-\",\"homeNo\":\"city3 \",\"nic\":\"88556699\",\"fullName\":\"samith\",\"lang\":\"en\"}"
}"
This is my response. i read this as a string.
JSONParser parser = new JSONParser();
Object jj;
InputStream is = new ByteArrayInputStream(theString.getBytes());
BufferedReader br1 = new BufferedReader(new InputStreamReader(is));
jj = parser.parse(new BufferedReader(br1));
JSONObject jsonObject = (JSONObject) jj;
if(jsonobject!=null){
String city= (String) jsonObject.get("city");
}
I would suggest you to use java objects and GSON to convert it to JSON to pass it within different pages.
public class Car {
public String brand = null;
public int doors = 0;
}
Here is an example of generating JSON from a Java object with GSON:
Car car = new Car();
car.brand = "Rover";
car.doors = 5;
Gson gson = new Gson();
String json = gson.toJson(car);
Its simple and easy to use.
https://github.com/google/gson
And these are some things you can do with GSON
I am using the JSON-simple library to parse the Json format. How can I append something to a JSONArray? For e.g. consider the following json
{
"a": "b"
"features": [{/*some complex object*/}, {/*some complex object*/}]
}
I need to append a new entry in the features.
I am trying to create a function like this:-
public void appendToList(JSONObject jsonObj, JSONObject toBeAppended){
JSONArray arr = (JSONArray)jsonObj.get("features");
//1) append the new feature
//2) update the jsonObj
}
How to achieve steps 1 & 2 in the above code?
You can try this:
public static void main(String[] args) throws ParseException {
String jsonString = "{\"a\": \"b\",\"features\": [{\"feature1\": \"value1\"}, {\"feature2\": \"value2\"}]}";
JSONParser parser = new JSONParser();
JSONObject jsonObj = (JSONObject) parser.parse(jsonString);
JSONObject newJSON = new JSONObject();
newJSON.put("feature3", "value3");
appendToList(jsonObj, newJSON);
System.out.println(jsonObj);
}
private static void appendToList(JSONObject jsonObj, JSONObject toBeAppended) {
JSONArray arr = (JSONArray) jsonObj.get("features");
arr.add(toBeAppended);
}
This will fulfill your both requirements.
Getting the array by: jsonObj["features"], then you can add new item by assign it as the last element in the array ( jsonObj["features"].length is the next free place to add new element)
jsonObj["features"][jsonObj["features"].length] = toBeAppended;
fiddle example
I'm trying to "create" a JSONObject. Right now I'm using JSON-Simple and I'm trying to do something along the lines of this (sorry if any typo's are made in this example JSON file)
{
"valuedata": {
"period": 1,
"icon": "pretty"
}
}
Right now I'm having issues finding on how to write valuedata into a JSON file through Java, what I did try was:
Map<String, String> t = new HashMap<String, String>();
t.put("Testing", "testing");
JSONObject jsonObject = new JSONObject(t);
but that just did
{
"Testing": "testing"
}
Whatr you want to do is put another JSONObject inside your JSONObject "jsonObject", in the field "valuedata" to be more exact. You can do this like that...
// Create empty JSONObect here: "{}"
JSONObject jsonObject = new JSONObject();
// Create another empty JSONObect here: "{}"
JSONObject myValueData = new JSONObject();
// Now put the 2nd JSONObject into the field "valuedata" of the first:
// { "valuedata" : {} }
jsonObject.put("valuedata", myValueData);
// And now add all your fields for your 2nd JSONObject, for example period:
// { "valuedata" : { "period" : 1} }
myValueData.put("period", 1);
// etc.
Following is example which shows JSON object streaming using Java JSONObject:
import org.json.simple.JSONObject;
class JsonEncodeDemo
{
public static void main(String[] args)
{
JSONObject obj = new JSONObject();
obj.put("name","foo");
obj.put("num",new Integer(100));
obj.put("balance",new Double(1000.21));
obj.put("is_vip",new Boolean(true));
StringWriter out = new StringWriter();
obj.writeJSONString(out);
String jsonText = out.toString();
System.out.print(jsonText);
}
}
While compile and executing above program, this will produce following result:
{"balance": 1000.21, "num":100, "is_vip":true, "name":"foo"}
Here is my json Object.
{"id":"mrbbt6f3fa99gld0m6n52osge0",
"name_value_list":
{"user_default_dateformat":{"name":"user_default_dateformat","value":"m/d/Y"}},
"module_name":"Users"}
I got id,and module_name through following code.How can i get user_default_dateformat?.
I know it may so simple but I am a newbie in json.
String jsonResponse;
while ((jsonResponse = br.readLine()) != null) {
jsonOutput = jsonResponse;
}
JSONObject job = new JSONObject(jsonOutput);
System.out.println(job);// i can see the same json object
that i showen above.
sessionID = job.get("id").toString();
Exception generating coge
JSONObject job2=new JSONObject(job);
dateFormat = job2.get("user_default_dateformat").toString();
The Eexception is
org.json.JSONException: JSONObject["user_default_dateformat"] not found.
Thanks,
name_value_list is also an Object.
JSONObject job2 = new JSONObject(job.get("name_value_list"));
So there you get
job2.get("user_default_dateformat");
Every {} in your JSON is an object. So for every String you get which is something like {"xy":"za","ab":"cd"} you have to cast it to the JSONObject
Edit for your error:
As you can see in your code the line:
JSONObject job2=new JSONObject(job);
will try to generate a JSONObject out of your JSONObject.
You have to get the JSONObject in your JSONObject.
You want to get the user_default_dateformat which is in your JSONObject:
String name_value_list_string = job.get("name_value_list").toString();
//this string is another json-string which contains the user_default_dateformat
JSONObject name_value_list_object = new JSONObject(name_value_list_string);
//This JSONObject contains the user_default_dateformat but this is also a JSONObject
String user_default_dateformat_string = name_value_list_object.get("user_default_dateformat").toString();
//this String contains the user_default_dateformat JSONString
JSONObject user_default_dateformat_object = new JSONObject(user_default_dateformat_string);
//This JSONObject contains the String values of your user_default_dateformat
if you are using JSONSimple library you can use this:
jsonObject = (JSONObject) new JSONParser().parse(jsonstr);
System.out.println((JSONObject)jsonObject.get("name_value_list"))).get("user_default_dateformat"));
This should give you the required result.