I'm getting a HTTP GET response like this:
(yeah, I know it's weird)
1,24,https://www.myweb.com/img/BTMz_shave_club.png|10,21,https://www.myweb.com/img/BTMz_coffee_club.png|30,22,https://www.myweb.com/img/BTMz_coffee_club.png|
I need to split the String by "|". And then split "," and result is something like:
[
{id: 1, qty: 24, img_uri: https://www.myweb.com/img/BTMz_shave_club.png},
{id: 10, qty: 21, img_uri: https://www.myweb.com/img/BTMz_coffee_club.png},
{id: 22, qty: 22, img_uri: https://www.myweb.com/img/BTMz_coffee_club.png}
]
It's a String response, but I need to convert it to an JSONArray.
Thanks for the help.
try something like
private void splitAndMakeJson() {
JSONArray jsonArray=new JSONArray();
JSONObject jsonObject=null;
String mainString="1,24,https://www.myweb.com/img/BTMz_shave_club.png|10,21,https://www.myweb.com/img/BTMz_coffee_club.png|30,22,https://www.myweb.com/img/BTMz_coffee_club.png|";
String[] mainToken=mainString.split("\\|");
for(int i=0;i<mainToken.length;i++){
String subToken[]=mainToken[i].split(",");
jsonObject=new JSONObject();
try {
jsonObject.put("id",subToken[0].getBytes().toString());
jsonObject.put("qty",subToken[1].getBytes().toString());
jsonObject.put("img_uri",subToken[2].getBytes().toString());
jsonArray.put(jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
}
Log.e("Json",jsonArray.toString());
}
Related
During Login time i got this error, please don't downgrade this if you know any solution please guide me. I also checked different stack overflow post but they all are talking about trim the string or other solution with retrofit but i can't solve it. I use volley.
My Json File:-
{
"error": false,
"user": [
{
"user_id": "123",
"customer_name": "Abc",
"email": "abc#example.com",
"salt": "123abc",
"phone": "1234567890",
"address": "Enter Address",
"postal_code": "1234"
}
]
}
This is my Java Class :-
#Override
protected String doInBackground(Boolean... booleen) {
ExampleApi exampleApi = new ExampleApi();
LoginUser result;
try {
result = exampleApi.loginPost(sharedPreferences.getString("abc_id", ""), semail, fcmToken, spassword);
Gson gson = new Gson();
String json = gson.toJson(result);
JSONObject jObj = new JSONObject(json);
Log.e("result1", String.valueOf(jObj));
if (jObj.getString("error").equalsIgnoreCase("false")) {
JSONArray jsonArray = jObj.getJSONArray("user");
JSONObject jsonObject1 = jsonArray.getJSONObject(0);
return "true";
}else {
String errormsg = jObj.getString("error_msg");
return errormsg;
}
} catch (ApiException e) {
e.printStackTrace();
Log.e("error", e.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
Can you try initializing Gson as below
Gson gson = new GsonBuilder()
.setLenient()
.create();
Possibly there could be an issue in the expected JSON.
Check whether the properties of user object (user_id, customer_name. etc) are in correct format which is equal to the object received as response.
ps: If user_id is an Integer in your user object also it should be an Integer
In my case, this error was generated because of non UTF-8 json file encoding. When I convert it to UTF-8 all started to work.
I have this json code
{
"status": "success",
"message": null,
"data": {
"19": {
"id": "19",
"created": "2019-01-07 13:26:06",
"createdby": 158,
"touched": "2019-01-07 13:26:06",
"touchedby": 158,
"start": "2019-01-07",
"end": "2019-01-08",
"scoperole": 3,
"scopecorp": 1,
"body": "<p>test</p>",
"language": "en"
},
"20": {
"id": "20",
"created": "2019-01-07 13:26:20",
"createdby": 158,
"touched": "2019-01-07 13:26:20",
"touchedby": 158,
"start": "2019-01-07",
"end": "2019-01-08",
"scoperole": 3,
"scopecorp": 1,
"body": "<p>test1</p>",
"language": "en"
}
},
"error": 0,
"line": 1515,
"debug": null
}
And i want to take the values of "body" (test,test1).
How can i reach them?I left the code that i tried just to see it with //not working next to it.Any ideas please?Also the 19,20 are not the same so i'm not able to get them by just putting the name of a variable(ex JSONObject dataObj =new JSONObject ("data");
Here is my code
private void getJson() {
URL obj = null;
try {
obj = new URL("https://gekon.technologypark.cz/api/v1/notification/");
HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("ApiSecret", LoginInfo.ApiSecret);
conn.connect();
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
StringBuilder sb = new StringBuilder();
String output;
while ((output = br.readLine()) != null)
sb.append(output);
JSONObject jsonObj = new JSONObject(sb.toString());
Log.d("test", "response" + jsonObj);
JSONObject dataObj =new JSONObject("data");
JSONObject dataObj19 =dataObj.getJSONObject("22");
String body1 =dataObj19.getString("body");
Log.d("test", "TEST ID" + body1);
pushNotification(notifText);
} catch (Exception e) {
e.printStackTrace();
Log.d("test", "PUSH CATCH" + e);
}
}
Here are my logs
**2019-01-07 14:17:42.778 19712-19712/ibm.gekon.vasileiosvlachakis.gekon D/alekos:
response{"status":"success","message":null,"data":{"22":{"id":"22","created":"2019-01-07
14:11:55","createdby":158,"touched":"2019-01-07
14:11:55","touchedby":158,"start":"2019-01-07","end":"2019-01-08","scoperole":3,"scopecorp":1,"body":"test22</p>","language":"en"}},"error":0,"line":1515,"debug":null}
2019-01-07 14:17:42.785 19712-19712/ibm.gekon.vasileiosvlachakis.gekon
D/alekos: PUSH CATCHorg.json.JSONException: Value data of type
java.lang.String cannot be converted to JSONObject**
Here you can get the value of body key. but this is specific for 19 and 20 JSON object
JSONObject dataObj = new
JSONObject(sb.toString()).getJSONObject("data");
JSONObject dataObj19 =dataObj.getJSONObject("19");
String body1 =dataObj19.getString("body");
JSONObject dataObj20 =dataObj.getJSONObject("20");
String body2 =dataObj20.getString("body");
if Response has multiple JSON object inside data JSON object then you need a loop to retrieve it
JSONObject dataObj =new JSONObject("data");
for(int i=0;i<dataObj.length();i++){
JSONObject data =dataObj.getJSONObject(i);
String body =data .getString("body");
}
JSONObject json = new JSONObject(sb.toString());
String statistics = json.getString("data");
for(Iteraor key=json.keys();key.hasNext();) {
JSONObject keyValue = json.get(key.next());
//now keyValue contains the 19,20 and so on...
String body1 =keyValue.getString("body");
Log.d("test", "TEST ID" + body1);
}
Try this it might work.
best way is to make static key, but you can get all keys and then get value for each one
use
JSONObject dataObj =new JSONObject("data");
Iterator<String> keys=dataObj.keys();
while (keys.hasNext())
{
JSONObject currentObject =dataObj.getJSONObject(keys.next());
String currentBody =currentObject.getString("body");
Log.d("test", "TEST ID" + currentBody);
}`
In JSON response your key should always be static in order to get a particular response from the key.
Here check whether your data JSONObject contains that key or not for error handling.
try {
JSONObject jsonObj = new JSONObject(sb.toString());// assuming this as your main JSONObject
if(jsonObj.has("data")){
JSONObject dataObj =jsonObj.getJSONObject("data");
if(dataObj.has("19")){
JSONObject json19 = dataObj.getJSONObject("19");
// Now here check if the json19 contains the key that you want.
if(json19.has("body")){
String valueBody = json19.getString("body"); // this will give you the value of body
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
I'm working on parsing some JSON in my android application, this is the code I started off with:
JSONObject jsonObject = **new JSONObject(result);**
int receivedCount = **jsonObject.getInt("CurrentCount");**
However this is causing it to error (The code that would error is surrounded with asterisks) in Android Studio, I tried using the suggestion feature which asked me if I want "Surround with try/catch" which would cause the app to crash when it launched.
This is the suggested code:
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(result);
} catch (JSONException e) {
e.printStackTrace();
}
int receivedCount = 0;
try {
receivedCount = jsonObject.getInt("CurrentCount");
} catch (JSONException e) {
e.printStackTrace();
}
This is the JSON I'm trying to pass:
[{"CurrentCount":"5"},{"CurrentCount":"0"},{"CurrentCount":"1002"}]
Thanks in advance!
J_Dadh I think first of all you should look through the documentation on how to use Json Parser which you can find in the following Link https://www.tutorialspoint.com/android/android_json_parser.htm
EXAMPLE JSON
{
"sys":
{
"country":"GB",
"sunrise":1381107633,
"sunset":1381149604
},
"weather":[
{
"id":711,
"main":"Smoke",
"description":"smoke",
"icon":"50n"
}
],
"main":
{
"temp":304.15,
"pressure":1009,
}
}
String YourJsonObject = "JsonString"
JSONObject jsonObj = new JSONObject(YourJsonObject);
JSONArray weather = jsonObj.getJSONArray("weather");
for (int i = 0; i < weather.length(); i++) {
JSONObject c = weather.getJSONObject(i);
String id = c.getString("id");
String main= c.getString("main");
String description= c.getString("description");
}
as you pasted your JSON you are using [{"CurrentCount":"5"},{"CurrentCount":"0"},{"CurrentCount":"1002"}]
-If we analyze this JSON,This JSON contains a JSON ARRAY [{"CurrentCount":"5"},{"CurrentCount":"0"},{"CurrentCount":"1002"}]
having 3 JSON Objects{"CurrentCount":"5"},{"CurrentCount":"0"},{"CurrentCount":"1002"}
-But when you are going to parse this JSON, you are accepting it as jsonObject = new JSONObject(result),but you should accept it asJSONArray jsonArray=new JSONArray(result);
and then you iterate a loop(e.g,for loop) on this jsonArray,accepting JSONObjects 1 by 1,then getting the values from the each JSONObject 1 by 1.
-1 more mistake in your JSON is that you are sending the strings as "5" but accepting it as getInt() that's not fair,you should send int to accept it as intas 5 (without double qoutes)
So you final JSON and code like this(as below)
JSON
[{"CurrentCount":5},{"CurrentCount":0},{"CurrentCount":1002}]
Code to Use this JSON
JSONOArray jsonArray = null;
try{
jsonArray = new JSONArray(result);
for(int i=0;i<jsonArray.length;i++){
JSONObject jsonObject=jsonArray[i];
receivedCount=jsonObject.getInt("CurrentCount");
}
}catch(JSONException e) {
e.printStackTrace();
}
I have a problem to load this json in a JSONObject, i tried some combinations but it didn't work, for example i was able to load the Openweather JSON format easy but this one i got nothing on my Log as output
this is the format of Json:
{
"marcadores": [
{
"lat": 38.632682,
"id": 1,
"nombre": "Les Urques",
"mar": "appvalenciaplayas/static/images/mar/moderado.svg",
"viento": "appvalenciaplayas/static/images/viento/viento_S2.svg",
"simbolo": "appvalenciaplayas/static/images/cielo_dia/sol.svg",
"imagenTemp": "appvalenciaplayas/static/images/pastillas_temp/temp_25_a_31.svg",
"temperatura": 29,
"lon": 0.032945
},
{
"lat": 40.078478,
"id": 2,
"nombre": "Cala d'Orpesa la Vella",
"mar": "appvalenciaplayas/static/images/mar/debil.svg",
"viento": "appvalenciaplayas/static/images/viento/viento_SE2.svg",
"simbolo": "appvalenciaplayas/static/images/cielo_dia/nube_alta_sol.svg",
"imagenTemp": "appvalenciaplayas/static/images/pastillas_temp/temp_25_a_31.svg",
"temperatura": 31,
"lon": 0.134357
},
{
"lat": 40.008969,
"id": 3,
"nombre": "El Serradal",
"mar": "appvalenciaplayas/static/images/mar/debil.svg",
"viento": "appvalenciaplayas/static/images/viento/viento_SE2.svg",
"simbolo": "appvalenciaplayas/static/images/cielo_dia/nube_alta_sol.svg",
"imagenTemp": "appvalenciaplayas/static/images/pastillas_temp/temp_25_a_31.svg",
"temperatura": 31,
"lon": 0.034107
},
Thanks.
please put your response as a string in JSONObject
i am showing to you how to get all fields values like this
please read my code and apply my code as per your need.
try{
JSONObject json=new JSONObject(yourResponce);
JSONArray jarray=json.getJSONArray("marcadores");
for(int i=0;i<jarray.length;i++)
{
JSONObject jobj=jarray.getJSONObject(i);
String lat=jobj.getString("lat").toString();
String id=jobj.getString("id").toString();
String nombre=jobj.getString("nombre").toString();
String mar=jobj.getString("mar").toString();
String viento=jobj.getString("viento").toString();
String simbolo=jobj.getString("simbolo").toString();
String imagenTemp=jobj.getString("imagenTemp").toString();
String temperatura=jobj.getString("temperatura").toString();
String lon=jobj.getString("lon").toString();
}
}catch(Exception e)
{
e.printStackTrace();
}
Parse your JSON as follows
String str = "your_json_here";
try {
JSONObject jsonObject = new JSONObject(str);
JSONArray jsonArray = jsonObject.getJSONArray("marcadores");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject elementJsonObject = jsonArray.getJSONObject(i);
String id = elementJsonObject.getString("id");
// all fields to be accessed as above
}
} catch (JSONException e) {
e.printStackTrace();
}
Firstly, you need to create a POJO with attributes lat,id,nombre...
Read JSON array elements and convert JSON to Class (You can use jackson or Gson)
Use your object whatever you want
In addition this code piece may help you, but auto convertion is more pretty with some libs.
try{
JSONObject json=new JSONObject(yourResponce);
JSONArray jarray=json.getJSONArray("marcadores");
for(int i=0;i<jarray.length;i++)
{
JSONObject jobj=jarray.getJSONObject(i);
String lat=jobj.getString("lat").toString();
String id=jobj.getString("id").toString();
String nombre=jobj.getString("nombre").toString();
String mar=jobj.getString("mar").toString();
String viento=jobj.getString("viento").toString();
String simbolo=jobj.getString("simbolo").toString();
String imagenTemp=jobj.getString("imagenTemp").toString();
String temperatura=jobj.getString("temperatura").toString();
String lon=jobj.getString("lon").toString();
}}catch(Exception e) { e.printStackTrace(); }
Some other helpful links
https://www.mkyong.com/java/jackson-2-convert-java-object-to-from-json/
http://howtodoinjava.com/best-practices/google-gson-tutorial-convert-java-object-to-from-json/
Happy coding.
you can use Gson framework. You create a model class with the same Json response attributes/structure . This way you do not need to use getString( ) and getObject().
Example: https://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html
How to parse this below json response. I am developing a booking app. The response i got from the server is
{"HotelInformationResponse": {
"#hotelId": "210985",
"customerSessionId": "0ABAA826-9AAF-5791-3692-A03326791310",
"HotelSummary": {
"#order": "0",
"hotelId": 210985,
"name": "Seattle Marriott Waterfront",
"address1": "2100 Alaskan Way",
"city": "Seattle",
"stateProvinceCode": "WA",
"postalCode": 98121,
"countryCode": "US",
"propertyCategory": 1,
"hotelRating": 4,
"tripAdvisorRating": 4,
"locationDescription": "Near Seattle Aquarium",
"highRate": 645,
"lowRate": 279,
"latitude": 47.61016,
"longitude": -122.34651
},
"HotelDetails": {
"numberOfRooms": 358,
"numberOfFloors": 8,
"checkInTime": "4:00 PM",
"checkOutTime": "12:00 PM",
"propertyInformation": "Pets not allowed Check-in time starts at 4 PM Check-out time is Noon ",
}
Any method is appreciated
I hope this code can help u
public static String Profile_response(String response){
try{
JSONArray jsonarray = new JSONArray("["+response+"]");
JSONObject jsonobject = jsonarray.getJSONObject(0);
parseForcitydetail1(jsonobject.getString("HotelInformationResponse"));
return response;
}catch (Exception e) {
return "\"" + "Access Denied" + "\"";
}
}
public static void parseForcitydetail1(String res){
try{
JSONArray jsonarray1 = new JSONArray(res);
for(int i=0;i<jsonarray1.length();i++){
JSONObject jsonobject = jsonarray1.getJSONObject(i);
Hotal_ID.add(jsonobject.getString("#hotelId"));
customer_ID.add(jsonobject.getString("customerSessionId"));
}
parseForcitydetail2(jsonobject.getString("HotelSummary"));
}catch (Exception e) {
System.out.println(e.toString());
}
}
public static void parseForcitydetail2(String res){
try{
JSONArray jsonarray1 = new JSONArray(res);
for(int i=0;i<jsonarray1.length();i++){
JSONObject jsonobject = jsonarray1.getJSONObject(i);
Order.add(jsonobject.getString("#order"));
hote_ID.add(jsonobject.getString("hotelId"));
Name.add(jsonobject.getString("name")); Address.add(jsonobject.getString("address1"));....
City.add(jsonobject.getString("city"));
StateProvinceCode.add(jsonobject.getString("stateProvinceCode")); PostalCode.add(jsonobject.getString("postalCode"));
CountryCode.add(jsonobject.getString("countryCode"));
PropertyCategory.add(jsonobject.getString("propertyCategory")); HotelRating.add(jsonobject.getString("hotelRating"));....
TripAdvisorRating.add(jsonobject.getString("tripAdvisorRating"));
LocationDescription.add(jsonobject.getString("locationDescription")); Latitude.add(jsonobject.getString("latitude"));
Longitude.add(jsonobject.getString("longitude"));
}
}catch (Exception e) {
System.out.println(e.toString());
}
}
This Same process with "HotelDetails" Parsing
Enjoy !
You may use JSONArray and JSONObject to parse it manually. but its boring and may require extra attention to keys while running in loops. The easiest and highly recommended way is to use Google Gson library to handle this automatically.
Using JSONOBject, JSONArray to contain data like JSONObject, JSONArray
Using methods like: getJSONObject(), getString(), getXXX(). . to get data which you want.
with XXX - data type like int, string
You will understand how to parse JSON in Android easily with the link which describes how to parse JSON clearly (Example):
http://www.technotalkative.com/android-json-parsing/
private JSONObject jObject;
jObject = new JSONObject(your response as string);
//this will give you json object for HotelInformationResponse
JSONObject menuObject = jObject.getJSONObject("HotelInformationResponse");
by this way you can get values
String hotelId = menuObject.getString("#hotelId");
String customerSessionId = menuObject.getString("customerSessionId");
//...rest are same do same thing for HotelDetails
for extra information Check this link