Searching up on google I found this solution to read json strings from URL:
JSONObject json = new JSONObject(IOUtils.toString(new URL("https://somelink.com"), Charset.forName("UTF-8")));
The problem is that there is no JSONObject(String) constructor, why is that?
I thin you use google-gson, use org.json, there is constructor:
JSONObject obj = new JSONObject(str);
String myData = obj.getString("myData");
Related
I'm setting up a new server and android, and want to send base64(image) from android to server. I use JSON for data format between android and server, so I have to put my base64 into that JSON, but the server cannot decode my base64 because there are a symbol like "\n,+," and many more. I also try using Notepad for replace "\n" but still the server wont decode it..
note:
if I use Postman the server work properly
JSONArray data = new JSONArray();
for (int i = 0; i < listImage.size(); i++) {
//listImage.get(i).setBase64(map.get(listImage.get(i).getId()));
jsonObject = new JSONObject();
jsonObject.put("id",listImage.get(i).getId());
jsonObject.put("base64",map.get(listImage.get(i).getId()));
data.put(jsonObject);
}
jsonObject = new JSONObject();
jsonObject.put("image",data);
JSONObject has toString() method that return json object data into String format. You can also look at UTF encoding to encode special character, to make http request without conflicting of special character in URL.
jsonObject = new JSONObject();
jsonObject.put("image",data);
jsonObject.toString();
Easiest way to convert jason object to a String
JSONObject json = new JSONObject();
json.toString();
thank you for your answer guys...I have found my own solution, I need to replace "\n" and "\" with "" from base64 in server side
Actually, I have a JSONObject like this:
JSONObject json = new JSONObject();
json.put("type", "login");
json.put("friendList", FriendList);
and the FriendListis the type of ArrayList<String[]>
, then I use a socket to transfer JSON to my client.
My client received the data:
JSONObject receive_msg = new JSONObject(data);
String type = receive_msg.getString("type");
My question is how to get friendList with data typeArrayList<String[]>?
Thanks a lot if anyone helps.
you need to use JsonArray, iteratore over your list and fill the jsonArray then put it in the JsonObject
http://docs.oracle.com/javaee/7/api/javax/json/JsonArray.html
I am using HttpURLConnection from application1 to get json data from applicaton2. 'applicaton2' sets json data in Rest response object. How can i read that json data after getting response in application1.
Sample code:
Application1:
url = "url to application2";
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
Application2":
List<ModelA> lListModelAs = Entities data;
GenericEntity<List<ModelA>> lEntities = new GenericEntity<List<ModelA>>(lListModelAs) {};
lResponse = Response.ok(lEntities ).build();
I need to read above json data from urlConnection from response.
Any hints? Thanks in advance.
After setting up your HttpURLConnection.
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
JsonObject obj = new JsonParser().parse(reader).getAsJsonObject();
boolean status = contentObj.get("status").getAsBoolean();
String Message = contentObj.get("msg").getAsString();
String Regno = contentObj.get("regno").getAsString();
String User_Id = contentObj.get("userid").getAsString();
String SessionCode = contentObj.get("sesscode").getAsString();
You can download the gson jar here enter link description here
Use dedicated library for json serialization/deserialization, Jackson for example. It will allow you to read json content directly from InputStream into POJOs that maps the response. It will be something like that:
MyRestResponse response=objectMapper.readValue(urlConnection.getInput(),MyRestResponse.class);
Looking good isnt it??
Here you have Jackson project GitHub page with usage examples.
https://github.com/FasterXML/jackson
You can use gson library
https://github.com/google/gson for parsing your data
Gson gson = new Gson();
YourClass objOfYourClass = gson.fromJson(urlConnection.getInputStream(), YourClass.class);
I am farily new to the Jackson json classes. I have just donwloaded version 2.2.1 which seems to be the best version for the jdk 1.5 which is what we have.
I have some json that I am trying to parse nicely but would like some help on how to use the jackson classes. Can someone please help me with an example of how I could map the data into a java object?
Here is my json...
[{"status":"GREEN","businessDate":"2014-07-25","transactionCount":510620},{"status":"GREEN","businessDate":"2014-07-24","transactionCount":532435},{"status":"GREEN","businessDate":"2014-07-23","transactionCount":379355},{"status":"GREEN","businessDate":"2014-07-22","transactionCount":321474},{"status":"GREEN","businessDate":"2014-07-21","transactionCount":322975}]
Here is what the call on my server classes looks like...
String requestURI = "http://mycompany:9080/ReportingManager/service/repManHealth/importHistoryTrafficLightStatus.json";
URL url = new URL(requestURI);
URLConnection conn = url.openConnection();
InputStream in = conn.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(in));
StringBuffer sb = new StringBuffer();
String line = null;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
ObjectMapper mapper = new ObjectMapper();
// do some mapping here...
thanks
My question is can I use the jackson
Here is a small example:
ObjectMapper mapper = new ObjectMapper();
MyObject obj = mapper.readValue(sb.toString(), MyObject.class);
When MyObject is implemented in Bean Standard and the attribute names match the attribute names in JSON. All should work fine.
Otherwise use annotations to mapp your java object attributes correctly to the json attributes.
Thats all.
Jackson mapps the json objects to beans or pojos. You need to setup the beans having the fields like status, businessDate etc. For different names use annotations. And than you can use mapper to map the json string.
Using mapper your code looks like following
mapper.readValue(jsonString, YourBean.class);
Note here YourBean will be the POJO for holding json data.
I am trying to read results of a JSON request into java, yet
The partial output of my JSON request looks like this :
"route_summary": {
"total_distance": 740,
"total_time": 86,
"start_point": "Marienstraße",
"end_point": "Feldbergstraße"
}
I would like to use the standard json library to extract the values in total_distance.
However I only seem to be able to get the 'route_summary' by doing this :
JSONObject json = null;
json = readJsonFromUrl(request);
json.get("route_summary");
Where
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
What I want is get 'into' route_summary, any clue / tip would be great !
You need to get route_summary, as you already did, and from that object you need to get the total_distance. This will give you back the route_summary.total_distance.
Code sample:
JSONObject object = new JSONObject(s);
int totalDistance = object.getJSONObject("route_summary").getInt("total_distance");
I would recommend you to use GSON library. You can create class which will represent the message and then automatically map JSON to object by invoking function: gson.fromJson(message, YourMessageClass.class).getRoute_summary().
Here is the example of such approach: https://sites.google.com/site/gson/gson-user-guide/#TOC-Object-Examples