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;
}
Related
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);
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.
I am returning a json from my class:
#POST("/test")
#PermitAll
public JSONObject test(Map form) {
JSONObject json=new JSONObject();
json.put("key1",1);
json.put("key2",2);
return json;
}
now I want to get this json from "getInputStream" and parse it to see if key1 exists:
String output = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder output = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
output=output.toString();
JSONObject jsonObj = new JSONObject();
jsonObj.put("output", output);
if (jsonObj.get("output") != null){
**//search for key1 in output**
System.out.println("key1 exists");
}else{
System.out.println("key1 doesnt exist");
}
reader.close();
How can I convert output to JSONObject and search for "key1"?
I tried following but I got errors after arrows:
JSONObject jObject = new JSONObject(output); ---> The constructor JSONObject(String) is undefined
JSONObject data = jObject.getJSONObject("data"); ---> The method getJSONObject(String) is undefined for the type JSONObject
String projectname = data.getString("name"); ----> The method getString(String) is undefined for the type JSONObject
JSONObject jsonObject = (JSONObject) JSONValue.parse(output);
Try this.
And then you can verify the existence of the field using:
jsonObject.has("key1");
You need to parse the object using a parser. Check out the documentation here: https://code.google.com/p/json-simple/wiki/DecodingExamples
I'm new in java and i have this maybe simple faculty project. I must to parse json with eclipse, so i started but without any success. I don't know how to start when i have a multiple object in json.
I started like this:
public static void main(String[] args) {
FileReader reader = new FileReader(filePath);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
JSONArray objectArray = jsonObject.getJSONArray("product");
//JSONObject site= jsonSites.getJSONObject(1);
long elementaryProductId = (long) jsonObject[0].get("elementaryProductId");
System.out.println("The id is: " + elementaryProductId);'
And thi is my json file:
[{
"elementaryProductId":1,
"bonusMalus":30,
"deductible":500,
"comprehensive":1,
"partial":0,
"legacyPremium":130,
"product":{
"productId":2,
"garage":"true",
"constructionYear":1990,
"region":"East",
"dateOfBirthYoungest":"1983-06-22",
"objectValue":25000,
"type":"Car",
"insuredObject":{
"name":"Car",
"ownersName":"Jovana",
"mileage":300000,
"engineCapacity":120
},
"salesProduct":{
"salesProductId":3,
"currency":"EUR",
"contractStart":"2011-01-01",
"contractEnd":"2012-01-01"
},
"productType":"Car"
}
},
{
"elementaryProductId":1,
"bonusMalus":5,
"deductible":100,
"comprehensive":1,
"partial":0,
"legacyPremium":75.38,
"product":{
"productId":2,
"garage":"true",
"constructionYear":2005,
"region":"East",
"dateOfBirthYoungest":"1999-06-22",
"objectValue":30000,
"type":"Car",
"insuredObject":{
"name":"Car",
"ownersName":"Jelena",
"mileage":300000,
"engineCapacity":210
},
"salesProduct":{
"salesProductId":3,
"currency":"EUR",
"contractStart":"2013-01-01",
"contractEnd":"2014-01-01"
},
"productType":"Car"
}
}]
I got it to work with the following:
public static void main(String[] args) throws IOException, ParseException{
FileReader reader = new FileReader(new File("filename.json"));
JSONParser jsonParser = new JSONParser();
JSONArray jsonArray = (JSONArray) jsonParser.parse(reader);
JSONObject object = (JSONObject) jsonArray.get(0);
long elementaryProductId = (Long) object.get("elementaryProductId");
System.out.println("The id is: " + elementaryProductId);
}
Explanation of the above:
You know the outermost element is an array so parse straight into a JSONArray. Next you want to pull out the first element of that array which is a JSONObject (its in braces). After that the code should be fairly self explanatory :)
public static void main(String[] args) throws IOException {
try {
JSONObject json = new JSONObject(readUrl("http://api.wunderground.com" +"/api/106c4dee47162999/history_20060405/q/CA/San_Francisco.json"));
JSONObject data = json.getJSONObject("observations.tempm");
System.out.println(data);
} catch (JSONException e) {
e.printStackTrace();
}
}
private static String readUrl(String string) throws IOException {
BufferedReader reader = null;
try {
String urlString = string;
URL url = new URL(urlString);
reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuffer buffer = new StringBuffer();
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1)
buffer.append(chars, 0, read);
return buffer.toString();
} finally {
if (reader != null)
reader.close();
}
}
}
2.errors :
org.json.JSONException: JSONObject["observations.tempm"] not found.
at org.json.JSONObject.get(JSONObject.java:454)
at org.json.JSONObject.getJSONObject(JSONObject.java:553)
at com.parser.ParserObject.main(ParserObject.java:17)
The intersting part of the JSON you use is:
{'history':
{'observations':
[
{'tempm':'10.0'}
]
}
}
Use this:
JSONObject json = ...;
JSONObject history = (JSONObject) json.get("history");
JSONArray observations = (JSONArry) json.get("observations");
JSONObject observation0 = (JSONObject) observations.get(0);
String tempm = observation0.get("tempm");
If you are interested in other array elements, use a different index.
'observations' isnt in root. you need to get 'history' first. 'observations' is a part of 'history'. and 'observations' is a list/array.
i suggest using 'jackson' or 'gson' library.parsing native json is really a pain.
you can even go to a extent of un/marshalling only required fields/objects from JSON.