So far with the code I have, I am able to get results as a JsonObject. However, I am trying to get the coordinates of the location based on the postal code that I have entered. How can I retrieve the "lat" and "lng" as Strings/JsonElements? Would really appreciate if you can give me some insight. Thanks!
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("application/json");
//the JSON builder
Gson gson = new GsonBuilder().setPrettyPrinting().create();
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
String restaurant = request.getParameter("r");
String customer = request.getParameter("c");
//Get coordinates of the restaurant
String longLatApi = "https://maps.googleapis.com/maps/api/geocode/json?address=" + restaurant;
URL url = new URL(longLatApi);
URLConnection connection = url.openConnection();
connection.addRequestProperty("Referer", longLatApi);
String line;
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = reader.readLine()) != null) {
builder.append(line);
}
String jsonString = builder.toString();
JsonObject obj = new JsonParser().parse(jsonString).getAsJsonObject();
out.println(gson.toJson(obj));
JsonElement and its subclasses have nice methods to iterate through JSON elements of different kinds: null, a primitive (numbers, string literals, and booleans), a JSON object, or a JSON array. Knowing an exact structure of the response JSON document, you can extract child elements pretty straight-forward:
final URL url = new URL("https://maps.googleapis.com/maps/api/geocode/json?address=Greenwich");
// Let Gson parse the JSON input stream without expensive intermediate strings
try ( final Reader reader = new BufferedReader(new InputStreamReader(url.openStream())) ) {
final JsonParser jsonParser = new JsonParser();
// Extract the `results` array
final JsonArray resultsJsonArray = jsonParser.parse(reader)
.getAsJsonObject()
.get("results")
.getAsJsonArray();
// Iterate over each result array element
for ( int i = 0; i < resultsJsonArray.size(); i++ ) {
final JsonObject resultJsonObject = resultsJsonArray.get(i).getAsJsonObject();
System.out.println(resultJsonObject.getAsJsonPrimitive("formatted_address").getAsString());
// Picking up the `geometry` property as a JSON object
final JsonObject geometryJsonObject = resultJsonObject.get("geometry").getAsJsonObject();
// And dumping the location
final JsonObject locationJsonObject = geometryJsonObject.get("location").getAsJsonObject();
dumpLocationJsonObject("Location", locationJsonObject);
final JsonElement boundsJsonElement = geometryJsonObject.get("bounds");
// There can be a `bounds` object with two additional properties
if ( boundsJsonElement != null && !boundsJsonElement.isJsonNull() ) {
final JsonObject boundsJsonObject = boundsJsonElement.getAsJsonObject();
dumpLocationJsonObject("North/East", boundsJsonObject.get("northeast").getAsJsonObject());
dumpLocationJsonObject("South/West", boundsJsonObject.get("southwest").getAsJsonObject());
}
}
}
private static void dumpLocationJsonObject(final String name, final JsonObject location) {
final double latitude = location.getAsJsonPrimitive("lat").getAsDouble();
final double longitude = location.getAsJsonPrimitive("lng").getAsDouble();
System.out.println("\t" + name + ": (" + latitude + "; " + longitude + ")");
}
The output:
Greenwich, London SE10, UK
Location: (51.48257659999999; -0.0076589)
As an alternative approach, you can define custom JSON to Java classes mappings in order to deserialize the JSON document as a custom class instance, and not just JsonElement (something like gson.fromJson(reader, customType)). Both approaches have pros and cons.
Related
I created a post request with json and it works pretty well. But now I want to insert the output of this json post request into my database.
So I need to create a json parser to seperate the string like this: "Bestellnummer:1", "Besteller:8195529", "Zeit: 2019-09-27 15:50:07", "Artikelnummer:76194", "Anzahl:1", "Preis:2.968"... (next Artikelnummer and so on...).
Bestellnummer = orderid, Besteller = customerid, Zeit = time, Artikelnummer=articleid, Anzahl = number of article, Preis= price
I tried to do something like a parser in my code, but I never did something like this befor and unfortuntly don't know how to involve this parser in my code.
I hope u can help me
One example for my json Output:
{"Bestellnummer":"1","Besteller":"8195529","Zeit":"2019-09-27 15:50:07","Artikel":[{"Artikelnummer":"76194","Anzahl":"1","Preis":"2.968"},{"Artikelnummer":"61681","Anzahl":"1","Preis":"7.147"},{"Artikelnummer":"111756","Anzahl":"1","Preis":"9.29"},{"Artikelnummer":"14227","Anzahl":"1","Preis":"0"}]}
Code:
private static String dirPath = "https://hauteuchdrum.informatik.uni-siegen.de/propra/aufgaben/ws1920/index.php";
public ArrayList<String> Bestellung(){
File file = new File (dirPath + "//array_complex.json");
ArrayList <String> test = new ArrayList<String>();
try {
String str = "{ \"Bestellnummer\": [1,2,3,4,5] }";
// holt alle 47550 bestellungen vom json
for (int i=1; i<2;i++) {
String POST_PARAMS = "json={\"bid\":\"bid\", \"getorder\":\""+i+"\"}";
//System.out.println(POST_PARAMS);
JSONObject obj1 = new JSONObject(POST_PARAMS);
JSONArray arr=obj1.getJSONArray("Bestellnummer");
for (int z=0; z<arr.length();z++) {
String post_id = arr.getJSONObject(z).getString("Bestellnummer");
System.out.println(post_id);
}
URL obj = new URL("https://hauteuchdrum.informatik.uni-siegen.de/propra/aufgaben/ws1920/index.php");
HttpURLConnection postConnection = (HttpURLConnection) obj.openConnection();
postConnection.setRequestMethod("POST");
postConnection.setRequestProperty("connection", "Keep-Alive");
postConnection.setDoOutput(true);
java.io.OutputStream os = postConnection.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
int responseCode = postConnection.getResponseCode();
//System.out.println("POST Response Code : " + responseCode);
// System.out.println("POST Response Message : " + postConnection.getResponseMessage());
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(postConnection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
// System.out.println(response.toString());
test.add(response.toString());
// java.util.Iterator<String> it = test.iterator();
// while (it.hasNext()) {
// System.out.println(it.next());
// }
}
}
}
catch (Exception e) {
System.out.println();
}
return test;
}
If what you want to do is to insert the HTTP response string into database, I strongly recommend you to deserialize the string to POJOs as follows:
Declare 2 classes - MyResponse and Artikel. Artikel is for storing the content of JOSN object in JSON array, and I use List<Artikel> for the JSON array. BTW, I also use #JsonProperty(provided in Jackson) to map JSON keys with uppercase to variables with lowercase.
class MyResponse {
#JsonProperty(value="Bestellnummer")
private String bestellnummer;
#JsonProperty(value="Besteller")
private String besteller;
#JsonProperty(value="Zeit")
private String zeit;
#JsonProperty(value="Artikel")
private List<Artikel> artikel;
//general getters and setters
}
class Artikel {
#JsonProperty(value="Artikelnummer")
private String artikelnummer;
#JsonProperty(value="Anzahl")
private String anzahl;
#JsonProperty(value="Preis")
private String preis;
//general getters and setters
}
Now, you can use Jackson (one of the most popular JSON libraries) to deserialize the HTTP response to our POJOs. And you can manipulate these POJOs for DB operation easily.
ObjectMapper mapper = new ObjectMapper();
MyResponse myResponse = mapper.readValue(response.toString(), MyResponse.class);
myResponse.getArtikel().forEach(System.out::println);
Console output
Artikel [artikelnummer=76194, anzahl=1, preis=2.968]
Artikel [artikelnummer=61681, anzahl=1, preis=7.147]
Artikel [artikelnummer=111756, anzahl=1, preis=9.29]
Artikel [artikelnummer=14227, anzahl=1, preis=0]
Because you provided too less information to come up with a more detailed answer I came up with the following code.
JSONObject main = new JSONObject(data);
String orderNumber = main.getString("Bestellnummer"); // Retrieving the order number
String orderUserId = main.getString("Besteller"); // Retrieving the orderUserId
String time = main.getString("Zeit"); // Retrieving the current time
JSONArray articles = main.getJSONArray("Artikel"); // Getting articles as JSON Array
for (int i = 0; i < articles.length(); i++) { // Looping tough the articles
JSONObject article = articles.getJSONObject(i); // Getting the article JSON Object
String articleNumber = article.getString("Artikelnummer"); // Retrieving the Article number
String amount = article.getString("Anzahl"); // Retrieving the amount
String price = article.getString("Pris"); // Retrieving the price
// Your code...
}
I hope this helps you.
I have a trouble finding a way how to parse JSONArray.
It looks like this:
[{"name":"name1","url":"url1"},{"name":"name2","url":"url2"},...]
I know how to parse it if the JSON was written differently (In other words, if I had json object returned instead of an array of objects).
But it's all I have and have to go with it.
*EDIT: It is a valid json. I made an iPhone app using this json, now I need to do it for Android and cannot figure it out.
There are a lot of examples out there, but they are all JSONObject related. I need something for JSONArray.
Can somebody please give me some hint, or a tutorial or an example?
Much appreciated !
use the following snippet to parse the JsonArray.
JSONArray jsonarray = new JSONArray(jsonStr);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String name = jsonobject.getString("name");
String url = jsonobject.getString("url");
}
I'll just give a little Jackson example:
First create a data holder which has the fields from JSON string
// imports
// ...
#JsonIgnoreProperties(ignoreUnknown = true)
public class MyDataHolder {
#JsonProperty("name")
public String mName;
#JsonProperty("url")
public String mUrl;
}
And parse list of MyDataHolders
String jsonString = // your json
ObjectMapper mapper = new ObjectMapper();
List<MyDataHolder> list = mapper.readValue(jsonString,
new TypeReference<ArrayList<MyDataHolder>>() {});
Using list items
String firstName = list.get(0).mName;
String secondName = list.get(1).mName;
public static void main(String[] args) throws JSONException {
String str = "[{\"name\":\"name1\",\"url\":\"url1\"},{\"name\":\"name2\",\"url\":\"url2\"}]";
JSONArray jsonarray = new JSONArray(str);
for(int i=0; i<jsonarray.length(); i++){
JSONObject obj = jsonarray.getJSONObject(i);
String name = obj.getString("name");
String url = obj.getString("url");
System.out.println(name);
System.out.println(url);
}
}
Output:
name1
url1
name2
url2
Create a class to hold the objects.
public class Person{
private String name;
private String url;
//Get & Set methods for each field
}
Then deserialize as follows:
Gson gson = new Gson();
Person[] person = gson.fromJson(input, Person[].class); //input is your String
Reference Article: http://blog.patrickbaumann.com/2011/11/gson-array-deserialization/
In this example there are several objects inside one json array. That is,
This is the json array: [{"name":"name1","url":"url1"},{"name":"name2","url":"url2"},...]
This is one object: {"name":"name1","url":"url1"}
Assuming that you have got the result to a String variable called jSonResultString:
JSONArray arr = new JSONArray(jSonResultString);
//loop through each object
for (int i=0; i<arr.length(); i++){
JSONObject jsonProductObject = arr.getJSONObject(i);
String name = jsonProductObject.getString("name");
String url = jsonProductObject.getString("url");
}
public class CustomerInfo
{
#SerializedName("customerid")
public String customerid;
#SerializedName("picture")
public String picture;
#SerializedName("location")
public String location;
public CustomerInfo()
{}
}
And when you get the result; parse like this
List<CustomerInfo> customers = null;
customers = (List<CustomerInfo>)gson.fromJson(result, new TypeToken<List<CustomerInfo>>() {}.getType());
A few great suggestions are already mentioned.
Using GSON is really handy indeed, and to make life even easier you can try this website
It's called jsonschema2pojo and does exactly that:
You give it your json and it generates a java object that can paste in your project.
You can select GSON to annotate your variables, so extracting the object from your json gets even easier!
My case
Load From Server Example..
int jsonLength = Integer.parseInt(jsonObject.getString("number_of_messages"));
if (jsonLength != 1) {
for (int i = 0; i < jsonLength; i++) {
JSONArray jsonArray = new JSONArray(jsonObject.getString("messages"));
JSONObject resJson = (JSONObject) jsonArray.get(i);
//addItem(resJson.getString("message"), resJson.getString("name"), resJson.getString("created_at"));
}
Create a POJO Java Class for the objects in the list like so:
class NameUrlClass{
private String name;
private String url;
//Constructor
public NameUrlClass(String name,String url){
this.name = name;
this.url = url;
}
}
Now simply create a List of NameUrlClass and initialize it to an ArrayList like so:
List<NameUrlClass> obj = new ArrayList<NameUrlClass>;
You can use store the JSON array in this object
obj = JSONArray;//[{"name":"name1","url":"url1"}{"name":"name2","url":"url2"},...]
Old post I know, but unless I've misunderstood the question, this should do the trick:
s = '[{"name":"name1","url":"url1"},{"name":"name2","url":"url2"}]';
eval("array=" + s);
for (var i = 0; i < array.length; i++) {
for (var index in array[i]) {
alert(array[i][index]);
}
}
URL url = new URL("your URL");
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
BufferedReader reader;
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
//setting the json string
String finalJson = buffer.toString();
//this is your string get the pattern from buffer.
JSONArray jsonarray = new JSONArray(finalJson);
I need to convert JSON string to Object[].
I tried with link1 and link2 and did not help me.
Code how i get JSON string:
public static String getListJsonString() {
String getListsUrl = BASE_URL + "lists";
String result = "";
try {
URL url = new URL(getListsUrl);
URLConnection urlConnection = url.openConnection();
urlConnection.setRequestProperty("Authorization", "Basic " + getAuthStringEnc());
InputStream is = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
int numCharsRead;
char[] charArray = new char[1024];
StringBuffer sb = new StringBuffer();
while ((numCharsRead = isr.read(charArray)) > 0) {
sb.append(charArray, 0, numCharsRead);
}
result = sb.toString();
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
This is example of my JSON:
And after i must fill ChomboBox on this way (this is example):
Object[] lists = getLists();
for(Object list : lists){
System.out.println("fill combobox");
}
You can use Gson, TypeToken and JSONObject, example:
final static Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
final Type objectType = new TypeToken<Object>(){}.getType();
JSONObject obj = new JSONObject(result);
Vector<Object> lists = gson.fromJson(obj.toString(), objectType);
I suggest you should be using jackson lib. I linked a great quick tutorial that I find really clear and useful.
The idea behind jackson lib is that JSON format is a stringified Object format so you should be able to map it properly to java POJOs easily. (POJO = Plain old java object, which is an object with some fields, maybe some annotations on top of your fields and finally just getters and setters).
You can auto generate Jackson annotated POJOs classes from a json string using this link : http://www.jsonschema2pojo.org/ (just select "JSON" instead of "JSON SCHEMA", and maybe tune the other parameters depending on your need).
I can feel your pain sometimes it's hard to get a quick example up and running.
This is a very simple example how you can read your json document using Jackson library. You need a minimum of jackson-annotations-x.y.z.jar, jackson-core-x.y.z.jar and jackson-databind-x.y.z.jar files in a classpath.
https://github.com/FasterXML/jackson-databind/
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
public class TestJSON1 {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonObj;
String jsonStr = "{ \"list\": [ "
+ " {\"id\":\"1\", \"name\":\"test1\"}, "
+ " {\"id\":\"2\", \"name\":\"test2\"}, "
+ " {\"id\":\"3\", \"name\":\"test3\"} "
+ "]}";
jsonObj = mapper.readTree(jsonStr);
System.out.println(jsonObj.get("list"));
JsonNode jsonArr=jsonObj.get("list");
int count=jsonArr.size();
for (int idx=0; idx<count; idx++) {
jsonObj = jsonArr.get(idx);
System.out.println( jsonObj.get("id").asText()+"="+jsonObj.get("name").asText() );
}
}
}
I'm studying Spring Framework and I'm parsing JSON data but it shows:
Unexpected token LEFT BRACE({) at position 4.
However eclipse did not show any indication of an error.
Here is my controller source:
#RequestMapping(value = "/listcall.do", method = RequestMethod.GET)
public void home( #RequestParam("val") String id, HttpServletRequest request , HttpServletResponse response) throws JsonIOException, IOException, ParseException {
response.setCharacterEncoding("utf8");
response.setContentType("application/json");
String valuewhat = id ;
JsonArray jarraySend = new JsonArray();
//System.out.println(request.getParameter("val"));
JSONParser parse = new JSONParser();
FileReader fileReader = new FileReader("D:\\Spring\\sworkspace\\Calendar\\src\\main\\resources\\somelist.json");
Scanner sc = new Scanner(fileReader);
String inline = null;
while(sc.hasNext())
{
inline+=sc.nextLine();
}
JSONObject json = (JSONObject) parse.parse(inline);
JSONArray jarray_1 = (JSONArray) json.get("listing_property_type_information");
for(int i=0;i<jarray_1.size();i++) {
JSONObject jsonobj_1 = (JSONObject)jarray_1.get(i);
//JsonArray jsonarr_2 = (JsonArray) jsonobj_1.get("property_type_groups");
jarray_1 = (JSONArray) jsonobj_1.get("property_type_groups");
for(int j=0;j<jarray_1.size();j++) {
JSONObject jsonobj_2 = (JSONObject) jarray_1.get(j);
//something do.....
}
}
//jarray.add(json);
new Gson().toJson(jarray_1, response.getWriter());
}
I've been practicing to mimic functions like the AirBNB site.
JSON file is located at:
https://www.airbnb.co.kr/become-a-host/room <-Here is a scrolling copy
You should have a look at your inline variable.And you should declare this variable like thisString inline = ""; rather than String inline = null; which will make the string you spliced start with "null"
This means your json is bad. Eclipse cannot catch it because it is a runtime error.
public static String fetchFromJSONNext() throws FileNotFoundException, IOException, org.json.simple.parser.ParseException {
// String filename=System.getProperty("user.dir")+"\\src\\com\\test\\mtcn1.json";
String filename=System.getProperty("user.dir")+"\\src\\com\\test\\mtcn1.json";
//System.out.println(request.getParameter("val"));
JSONParser parse = new JSONParser();
FileReader fileReader = new FileReader(filename);
Scanner sc = new Scanner(fileReader);
String inline ="";
String sj ="";
while(sc.hasNext()){
inline+=sc.nextLine();
JSONObject jsonobj_2 = (JSONObject) parse.parse(inline);
//something do.....
Object g=jsonobj_2.get("result");
JSONObject h = (JSONObject) g;
sj=(String) h.get("wutaf_rpcmsg");
}
return sj;
}
I am reading multiple JSONObject from a file and converting into a string using StringBuilder.
These are the JSON Objects.
{"Lng":"-1.5908601","Lat":"53.7987816"}
{"Lng":"-2.5608601","Lat":"54.7987816"}
{"Lng":"-3.5608601","Lat":"55.7987816"}
{"Lng":"-4.5608601","Lat":"56.7987816"}
{"Lng":"-5.560837","Lat":"57.7987816"}
{"Lng":"-6.5608294","Lat":"58.7987772"}
{"Lng":"-7.5608506","Lat":"59.7987823"}
How to convert into a string?
Actual code is:-
BufferedReader reader = new BufferedReader(new InputStreamReader(contents.getInputStream()));
StringBuilder builder = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
builder.append(line);
}
}
catch(IOException e)
{
msg.Log(e.toString());
}
String contentsAsString = builder.toString();
//msg.Log(contentsAsString);
I tried this code
JSONObject json = new JSONObject(contentsAsString);
Iterator<String> iter = json.keys();
while(iter.hasNext())
{
String key = iter.next();
try{
Object value = json.get(key);
msg.Log("Value :- "+ value);
}catch(JSONException e)
{
//error
}
}
It just gives first object. How to loop them?
try this and see how it works for you,
BufferedReader in
= new BufferedReader(new FileReader("foo.in"));
ArrayList<JSONObject> contentsAsJsonObjects = new ArrayList<JSONObject>();
while(true)
{
String str = in.readLine();
if(str==null)break;
contentsAsJsonObjects.add(new JSONObject(str));
}
for(int i=0; i<contentsAsJsonObjects.size(); i++)
{
JSONObject json = contentsAsJsonObjects.get(i);
String lat = json.getString("Lat");
String lng = json.getString("Lng");
Log.i("TAG", lat + lng)
}
What you do is you are loading multiple JSON objects into one JSON object. This does not make sense -- it is logical that only the first object is parsed, the parser does not expect anything after the first }. Since you want to loop over the loaded objects, you should load those into a JSON array.
If you can edit the input file, convert it to the array by adding braces and commas
[
{},
{}
]
If you cannot, append the braces to the beginning of the StringBuilder and append comma to each loaded line. Consider additional condition to eliminate exceptions caused by inpropper input file.
Finally you can create JSON array from string and loop over it with this code
JSONArray array = new JSONArray(contentsAsString);
for (int i = 0; i < array.length(); ++i) {
JSONObject object = array.getJSONObject(i);
}