jsonobject cannot be converted with multiple input possibilities - android

i made a asynctask routine to comunicate to all my webservices that looks as follows:
protected String[] doInBackground(String... params) {
String parameterString = params[0];
// effectieve http request met de parameters toegevoegd
HttpClient client = new DefaultHttpClient();
HttpGet aanvraag = new HttpGet(server + parameterString);
// foutanalyse van de http request
try
{
HttpResponse antwoord = client.execute(aanvraag);
StatusLine statuslijn = antwoord.getStatusLine();
int statuscode = statuslijn.getStatusCode();
if(statuscode != 200){
Log.i("statuscode verzending", "statuscode= "+ statuscode);
return null;
}
InputStream jsonStream = antwoord.getEntity().getContent();
BufferedReader reader= new BufferedReader(new InputStreamReader(jsonStream));
StringBuilder builder = new StringBuilder();
String lijn;
while((lijn = reader.readLine())!= null){
builder.append(lijn);
}
String jsonData = builder.toString();
// hier beginnen we met de json data te ontmantelen
JSONArray json = new JSONArray(jsonData);
String[] data = new String[35];
Log.i("jsonparser", "lengte geretourde data " + json.length());
for (int i = 0; i < json.length(); i++)
{
data[i] = json.getString(i).toString();
}
return data;
}
catch (ClientProtocolException e){
e.printStackTrace();
}
catch (IOException e){
e.printStackTrace();
}
catch (JSONException e) {
e.printStackTrace();
}
return null;
}
i use the routine everytime i connect to a webservice for my app, (i have about 15 of them)
all these webservices are made (and used) by the programs my software supplier made
now i would like to connect to them with my android app
some of them are working
others don't
what i found out already in my search for this failure:
some jsondata is returned in the form of:
[
"42416",
" ",
" ",
" "
]
other webservices return data as:
true
but the ones i am strugling with the most are looking like:
{
"z00": "1 ",
"z01": 10000,
"z02": "18/06/2010",
"z03": "A",
"z04": "0000",
"z05": 7735,
"z06": "VANNUYSE BVBA",
"z07": "DEEFA",
"z08": 17170,
"z09": "AFLEVEREN HELI IN GEBRUIK",
"z10": "0000",
"z11": "8770 ",
"z12": "INTER ",
"z13": "HELI ",
"z14": "CPCD25 - C240 ",
"z15": "48182 ",
"z16": "",
"z17": "N",
"z18": "0030",
"z19": 0,
"z20": "X",
"z21": " ",
"z22": "J",
"z23": "",
"z24": 0,
"z25": "22/06/2010",
"z26": 16854,
"z27": 0,
"z28": "AFLEVEREN IN GEBRUIK",
"z29": " "
}
how should i form my asynctask routine so she is able to work for all routines?
because my routine works fine now for the first type of data but at 3th type i get an error (didn't tried yet for 2nd type) :
JSONObject cannot be converted to JSONArray
thanks already for al your help guys

If you don't know what(jsonObject or jsonArray) is coming, you may try something like this:
try {
JSONObject jsonObject = new JSONObject(jsonData);
// handle jsonObject
} catch (JSONException e) {
// Try to parse it to a JSONAray.
// Also you can check the exception message here to determine if jsonArray conversion is wanted
try {
JSONArray jsonArray = new JSONArray(jsonData);
// handle jsonArray
} catch (JSONException e) {
// something which is not JsonObject or JsonArray!
}
}
Or try this:
Object jsonAsObject = new JSONTokener(jsonData).nextValue();
if (jsonAsObject instanceof JSONObject) {
// it is JSONObject
JSONObject jsonObject = (JSONObject) jsonAsObject;
} else if (jsonAsObject instanceof JSONArray) {
// it is JSONArray
JSONArray jsonArray = (JSONArray) jsonAsObject;
}

Related

How to parse this wikipedia response?

{
"batchcomplete": "",
"query": {
"pages": {
"25675557": {
"pageid": 25675557,
"ns": 0,
"title": "Cricket",
"extract": "Cricket is a bat-and-ball game played between two teams of eleven players each on a cricket field, at the centre of which is a rectangular 22-yard-long (20 metres) pitch with a target at each end called the wicket (a set of three wooden stumps upon which two bails sit). "
}
}
}
}
this is the code I tried :
public void getJSON(final String city) throws JSONException {
new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
try {
URL url = new URL("https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=" + city);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
BufferedReader reader =
new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuffer json = new StringBuffer(1024);
String tmp = "";
while ((tmp = reader.readLine()) != null) {
json.append(tmp).append("\n");
}
reader.close();
data = new JSONObject(json.toString());
if (data.getInt("cod") != 200) {
System.out.println("Cancelled");
return null;
}
} catch (Exception e) {
System.out.println("Exception " + e.getMessage());
return null;
}
return null;
}
#Override
protected void onPostExecute(Void Void) {
if (data != null) {
Log.d("my weather received", data.toString());
try {
//JSONObject forecastJson = new JSONObject(data);
JSONObject forecastArray = data.getJSONObject("query");
System.out.println(forecastArray);
JSONArray pagesArray = forecastArray.getJSONArray("pages");
// JSONArray idArray = pagesArray.getJSONArray(0);
//JSONArray idArray = pagesArray.get(0);
System.out.println(pagesArray);
JSONObject obj = pagesArray.getJSONObject(0);
System.out.println(obj);
//JSONObject weatherarray = data.getJSONObject("pages");
//JSONObject weather = weatherarray.getJSONObject(0);
// final String des = weather.getString("description");
/*for (int i = 0; i < forecastArray.length(); i++) {
JSONObject dailyForecast = forecastArray.getJSONObject(i);
JSONObject tempObject = dailyForecast.getJSONObject("main");
minTemp = tempObject.getDouble("min");
maxTemp = tempObject.getDouble("max");
//add these minTemp and maxTemp to array or the
//way you want to use
}*/
System.out.println("Temp Value : "+" : ");
runOnUiThread(new Runnable() {
#Override
public void run() {
textvw.setText("");
}
});
} catch (Exception e) {
Log.e("GetFeedTask", "Error:" + e.getMessage());
}
}
}
}.execute();
}
The exception is because the response does not contain JSON Array. Change your
JSONArray pagesArray = forecastArray.getJSONArray("pages");
to
JSONObject pagesArray = forecastArray.getJSONObject("pages");
and I believe that you're trying to get keys which are dynamic. You cloud get the objects using JSONObject.getKeys() like below.
Iterator keys = pagesArray.keys();
while(keys.hasNext()) {
String dynamicKey = (String)keys.next();
JSONObject jObj = pagesArray.getJSONObject(dynamicKey);
//Get other attributes by jObj.getString() method.
}
Try and let me know if it works.
The error is clear enough. you try to assign a JSONobject to a JSONArray
JSONArray pagesArray = forecastArray.getJSONArray("pages");
Replace by
JSONObject pagesArray = forecastArray.JSONObject("pages");
the data of a JSONArray are between [] and not {}.
your error is in :
JSONArray pagesArray = forecastArray.getJSONArray("pages");
Your problem is that you getJSONArray while pages are a JsonObject in your data .if your "pages" is a array in your data you must send it in [] from server like this:
{
"batchcomplete": "",
"query": {
"pages": [ {
"pageid": 25675557,
"ns": 0,
"title": "Cricket",
"extract": "Cricket is a bat-and-ball game played between two teams of eleven players each on a cricket field, at the centre of which is a rectangular 22-yard-long (20 metres) pitch with a target at each end called the wicket (a set of three wooden stumps upon which two bails sit). "
},
{
"pageid": 25675557,
"ns": 0,
"title": "Cricket",
"extract": "Cricket is a bat-and-ball game played between two teams of eleven players each on a cricket field, at the centre of which is a rectangular 22-yard-long (20 metres) pitch with a target at each end called the wicket (a set of three wooden stumps upon which two bails sit). "
}
]
}
}
and in android :
try {
//JSONObject forecastJson = new JSONObject(data);
JSONObject forecastArray = data.getJSONObject("query");
System.out.println(forecastArray);
JSONArray pagesArray = forecastArray.getJSONArray("pages");
System.out.println(pagesArray);
for (int k = 0; k < pagesArray.length(); k++) {
try {
JSONObject object = pagesArray.getJSONObject(k);
String pageid = object.getString("pageid");
String ns = object.getString("ns");
String title = object.getString("title");
String extract = object.getString("extract");
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
Log.e("GetFeedTask", "Error:" + e.getMessage());
}

How to fetch json array inside array in android listview

I'm having json format as below , How do i fetch it into listview in android, While i'm trying to do, following error rises. I,m having multiple starting array square brackets.
org.json.JSONException: Value [{"id":"30","title":"Android Design Engineer","postedDate":"2016-11-19","jobtype":"Contract","location":"Alabama","description":"Basic knowladge in android can give him so many advantages to develop and learna android in an openly sourced android developer in India and hes an outsourcer of the manditory field in and entire world","experience":"2 to 6 yrs","salary":" Upto $50"}] at 0 of type org.json.JSONArray cannot be converted to JSONObject
and the following my java code is, here i call jsosarray and split it into objects.
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://10.0.3.2/utyessjobsi/jobdetail");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
int code = httpResponse.getStatusLine().getStatusCode();
String recode = String.valueOf(code);
HttpEntity entity = httpResponse.getEntity();
is = entity.getContent();
bufferedReader = new BufferedReader(new InputStreamReader(is));
json_result = bufferedReader.readLine();
try {
if (code == 200) {
JSONArray jsonArray = new JSONArray(json_result);
int length = jsonArray.length();
for (int i = 0; i < length; i++) {
JSONObject c = jsonArray.getJSONObject(i);
String id = c.getString(TAG_ID);
String jobname = c.getString(TAG_JOBTITLE);
String description = c.getString(TAG_DESC);
String jobtype = c.getString(TAG_JOBTYPE);
String salary = c.getString(TAG_SALARY);
String postedon = c.getString(TAG_POSTEDDATE);
String location = c.getString(TAG_LOCATION);
String exp = c.getString(TAG_EXPE);
HashMap<String, String> result = new HashMap<String, String>();
result.put(TAG_ID, id);
result.put(TAG_JOBTITLE, jobname);
result.put(TAG_DESC, description);
result.put(TAG_JOBTYPE, jobtype);
result.put(TAG_SALARY, salary);
result.put(TAG_POSTEDDATE,postedon);
result.put(TAG_LOCATION, location);
result.put(TAG_EXPE, exp);
resultList.add(result);
}
} else {
JSONObject jsonObj = new JSONObject(json_result);
status = jsonObj.getString("status");
msg = jsonObj.getString("msg");
}
return recode;
} catch (JSONException e) {
Log.e("Json erroe", e.toString());
return e.toString();
My Json array
[
[
{
"id": "30",
"title": "Android Design Engineer",
"description": "Basic knowladge in android can give him so many advantages to develop and learna android in an openly sourced android developer in India and hes an outsourcer of the manditory field in and entire world",
"jobtype": "Contract",
"salary": " Upto $50",
"postedDate": "2016-11-19",
"location": "Alabama",
"experience": "2 to 6 yrs"
}
],
[
{
"id": "24",
"title": "Android Application Developer",
"description": "Android Application Developer is the major Development Technique that is used in this damn World.",
"jobtype": "Contract",
"salary": " Upto $50",
"postedDate": "2016-11-16",
"location": "North Carolina",
"experience": "6 to 10 yrs"
}
]
]
Check below parsing logic as per your JSON:
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://10.0.3.2/utyessjobsi/jobdetail");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
int code = httpResponse.getStatusLine().getStatusCode();
String recode = String.valueOf(code);
HttpEntity entity = httpResponse.getEntity();
is = entity.getContent();
bufferedReader = new BufferedReader(new InputStreamReader(is));
json_result = bufferedReader.readLine();
try {
if (code == 200) {
JSONArray jsonArray = new JSONArray(json_result);
if (jsonArray != null && jsonArray.length() > 0) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONArray jsonChildArray = jsonArray.getJSONArray(i);
if (jsonChildArray != null && jsonChildArray.length() > 0) {
JSONObject c = jsonChildArray.getJSONObject(0);
String id = c.getString(TAG_ID);
String jobname = c.getString(TAG_JOBTITLE);
String description = c.getString(TAG_DESC);
String jobtype = c.getString(TAG_JOBTYPE);
String salary = c.getString(TAG_SALARY);
String postedon = c.getString(TAG_POSTEDDATE);
String location = c.getString(TAG_LOCATION);
String exp = c.getString(TAG_EXPE);
HashMap<String, String> result = new HashMap<String, String>();
result.put(TAG_ID, id);
result.put(TAG_JOBTITLE, jobname);
result.put(TAG_DESC, description);
result.put(TAG_JOBTYPE, jobtype);
result.put(TAG_SALARY, salary);
result.put(TAG_POSTEDDATE, postedon);
result.put(TAG_LOCATION, location);
result.put(TAG_EXPE, exp);
resultList.add(result);
}
}
}
} else {
JSONObject jsonObj = new JSONObject(json_result);
status = jsonObj.getString("status");
msg = jsonObj.getString("msg");
}
return recode;
} catch (JSONException e) {
Log.e("Json erroe", e.toString());
return e.toString();
}
} catch (Exception e) {
Log.e("erroe", e.toString());
return e.toString();
}
Yes .There is an error.Your JSON Data has An array inside array and you are trying to assign internal array as object.
First convert outer array JsonArray jsonArray1;
Iterate through this array. i=0 -> jsonArray1.length; and create another
JsonArray jsonArray2 = jsonArray1[i];
And finally iterate through jsonArray2: j=0 -> jsonArray2.length()
and create a JsonObject json = jsonArray2[j];
I hope you understood. This is psuedocode. If you want code, tell me.I can write it.

Test the number of json object

i made this but i want to change while loop to do-while it's inferior to the maximum JsonObjet for example if i have 2 Json objects i would like to do the loop twice:
String ajout1 = "my adress";
JSONObject json = null;
String str = "";
HttpResponse response;
HttpClient myClient = new DefaultHttpClient();
HttpPost myConnection = new HttpPost(ajout1);
try {
response = myClient.execute(myConnection);
str = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
json = new JSONObject(str);
String module = json.getJSONObject("1").getString("id_module");
String address = json.getJSONObject("1").getString("adresse_mac");
String mdp = json.getJSONObject("1").getString("mot_de_passe");
String nom = json.getJSONObject("1").getString("name");
String module2 = json.getJSONObject("2").getString("id_module"); //from 2nd object
db.execSQL("INSERT INTO test21 (mac,mdp,obj,puce) VALUES('"+address+"','"+mdp+"','"+nom+"','"+module+"');");
} catch (JSONException e) {
e.printStackTrace();
}
}
my Json looks like this :
{
"1": {
"id_module": "f83d6101cc",
"adresse_mac": "00:6A:8E:16:C6:26",
"mot_de_passe": "mp0001",
"name": "a"
},
"2": {
"id_module": "64eae5403b",
"adresse_mac": "00:6A:8E:16:C6:26",
"mot_de_passe": "mp0002",
"name": "a"
}
}
Use the following way to parse
try {
json = new JSONObject(str);
Iterator<String> it=json.keys();
while(it.hasNext()){
String key=it.next();// 'key' contains values like 1 ,2 etc..
JSONObject element=json.getJSONObject("key");
//Perform your parsing...
}
} catch (JSONException e) {
e.printStackTrace();
}
Alternately (as indicated to you) its a better idea to use JSONArray.
You can call the keys() method of the JSONObject, the method retrieve you a Iterator of Strings with the keys contained in the object.
You only need add a while like this:
Iterator<String> iterator = json.keys();
while(iterator.hasNext()){
String key = iterator.next();
JSONObject jsonObject = json.getJSONObject(key);
//All you other code
}
Something like this would do I suppose:
JSONArray getInfo = yourJsonObject.getJSONArray();
then loop through using something like this
while(i < getInfo.length()){
//do stuffs here
}
and that will loop through however many JSONObject you have

Android parse JSONObject

I've got a little problem with parsing json into my android app.
This is how my json file looks like:
{
"internalName": "jerry91",
"dataVersion": 0,
"name": "Domin91",
"profileIconId": 578,
"revisionId": 0,
}
As You can see this structure is a little bit weird. I dont know how to read that data in my app. As I noticed those are all Objects not arrays :/
You can always use good old json.org lib. In your Java code :
First read your json file content into String;
Then parse it into JSONObject:
JSONObject myJson = new JSONObject(myJsonString);
// use myJson as needed, for example
String name = myJson.optString("name");
int profileIconId = myJson.optInt("profileIconId");
// etc
UPDATE 2018
After 5 years there is a new "standard" for parsing json on android. It's called moshi and one can consider it GSON 2.0. It's very similar but with design bugs fixed that are the first obstacles when you start using it.
https://github.com/square/moshi
First add it as a mvn dependency like this:
<dependency>
<groupId>com.squareup.moshi</groupId>
<artifactId>moshi-kotlin</artifactId>
<version>1.6.0</version>
</dependency>
After adding it we can use like so (taken from the examples):
String json = ...;
Moshi moshi = new Moshi.Builder().build();
JsonAdapter<BlackjackHand> jsonAdapter = moshi.adapter(BlackjackHand.class);
BlackjackHand blackjackHand = jsonAdapter.fromJson(json);
System.out.println(blackjackHand);
More infos on their GitHub page :)
[old]
I would recommend using Gson.
Here are some links for tutorials:
how to convert java objecto from json format using GSON
Parse JSON file using GSON
Simple GSON example
Converting JSON data to Java object
An alternative to Gson you could use Jackson.
Jackson in 5 minutes
how to convert java object to and from json
This libraries basically parse your JSON to a Java class you specified.
to know if string is JSONArray or JSONObject
JSONArray String is like this
[{
"internalName": "blaaa",
"dataVersion": 0,
"name": "Domin91",
"profileIconId": 578,
"revisionId": 0,
},
{
"internalName": "blooo",
"dataVersion": 0,
"name": "Domin91",
"profileIconId": 578,
"revisionId": 0,
}]
and this String as a JSONOject
{
"internalName": "domin91",
"dataVersion": 0,
"name": "Domin91",
"profileIconId": 578,
"revisionId": 0,
}
but how to call elements from JSONArray and JSONObject ?
JSNOObject info called like this
first fill object with data
JSONObject object = new JSONObject(
"{
\"internalName\": \"domin91\",
\"dataVersion\": 0,
\"name\": \"Domin91\",
\"profileIconId\": 578,
\"revisionId\": 0,
}"
);
now lets call information from object
String myusername = object.getString("internalName");
int dataVersion = object.getInt("dataVersion");
If you want to call information from JSONArray you must know what is the object position number or you have to loop JSONArray to get the information for example
looping array
for ( int i = 0; i < jsonarray.length() ; i++)
{
//this object inside array you can do whatever you want
JSONObject object = jsonarray.getJSONObject(i);
}
if i know the object position inside JSONArray ill call it like this
//0 mean first object inside array
JSONObject object = jsonarray.getJSONObject(0);
This part do in onBackground in AsyncTask
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url);
try {
result = json.getString("internalName");
data=json.getString("dataVersion");
ect..
} catch (JSONException e) {
e.printStackTrace();
}
JsonParser
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
I suggest you to use a library like gson as #jmeier wrote on his answer. But if you want to handle json with android's defaults, you can use something like this:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String s = new String("{\"internalName\": \"domin91\",\"dataVersion\": 0,\"name\": \"Domin91\",\"profileIconId\": 578,\"revisionId\": 0,}");
try {
MyObject myObject = new MyObject(s);
Log.d("MY_LOG", myObject.toString());
} catch (JSONException e) {
Log.d("MY_LOG", "ERROR:" + e.getMessage());
}
}
private static class MyObject {
private String internalName;
private int dataVersion;
private String name;
private int profileIconId;
private int revisionId;
public MyObject(String jsonAsString) throws JSONException {
this(new JSONObject(jsonAsString));
}
public MyObject(JSONObject jsonObject) throws JSONException {
this.internalName = (String) jsonObject.get("internalName");
this.dataVersion = (Integer) jsonObject.get("dataVersion");
this.name = (String) jsonObject.get("name");
this.profileIconId = (Integer) jsonObject.get("profileIconId");
this.revisionId = (Integer) jsonObject.get("revisionId");
}
#Override
public String toString() {
return "internalName=" + internalName +
"dataVersion=" + dataVersion +
"name=" + name +
"profileIconId=" + profileIconId +
"revisionId=" + revisionId;
}
}
}
Please checkout ig-json parser or Logan Square for fast and light JSON library.
For comparison, this is the stats from Logan Square developer.
Here you can parse any file from assets folder
fetch file from assets folder
public void loadFromAssets(){
try {
InputStream is = getAssets().open("yourfile.json");
readJsonStream(is);
} catch (IOException e) {
e.printStackTrace();
}
}
Convert JSON to your class object
public void readJsonStream(InputStream in) throws IOException {
Gson gson = new Gson();
JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
reader.setLenient(true);
int size = in.available();
Log.i("size", size + "");
reader.beginObject();
long starttime=System.currentTimeMillis();
while (reader.hasNext()) {
try {
Yourclass message = gson.fromJson(reader, Yourclass.class);
}
catch (Exception e){
Toast.makeText(this, e.getCause().toString(), Toast.LENGTH_SHORT).show();
}
}
reader.endObject();
long endtime=System.currentTimeMillis();
long diff=endtime-starttime;
int seconds= (int) (diff/1000);
Log.i("elapsed",seconds+"");
reader.close();
}

conversion from string to JSON object Android

I am working on an Android application. In my app I have to convert a string to JSON Object, then parse the values. I checked for a solution in Stackoverflow and found similar issue here link
The solution is like this
`{"phonetype":"N95","cat":"WP"}`
JSONObject jsonObj = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
I use the same way in my code . My string is
{"ApiInfo":{"description":"userDetails","status":"success"},"userDetails":{"Name":"somename","userName":"value"},"pendingPushDetails":[]}
string mystring= mystring.replace("\"", "\\\"");
And after replace I got the result as this
{\"ApiInfo\":{\"description\":\"userDetails\",\"status\":\"success\"},\"userDetails\":{\"Name\":\"Sarath Babu\",\"userName\":\"sarath.babu.sarath babu\",\"Token\":\"ZIhvXsZlKCNL6Xj9OPIOOz3FlGta9g\",\"userId\":\"118\"},\"pendingPushDetails\":[]}
when I execute JSONObject jsonObj = new JSONObject(mybizData);
I am getting the below JSON exception
org.json.JSONException: Expected literal value at character 1 of
Please help me to solve my issue.
Remove the slashes:
String json = {"phonetype":"N95","cat":"WP"};
try {
JSONObject obj = new JSONObject(json);
Log.d("My App", obj.toString());
} catch (Throwable t) {
Log.e("My App", "Could not parse malformed JSON: \"" + json + "\"");
}
This method works
String json = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";
try {
JSONObject obj = new JSONObject(json);
Log.d("My App", obj.toString());
Log.d("phonetype value ", obj.getString("phonetype"));
} catch (Throwable tx) {
Log.e("My App", "Could not parse malformed JSON: \"" + json + "\"");
}
try this:
String json = "{'phonetype':'N95','cat':'WP'}";
You just need the lines of code as below:
try {
String myjsonString = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";
JSONObject jsonObject = new JSONObject(myjsonString );
//displaying the JSONObject as a String
Log.d("JSONObject = ", jsonObject.toString());
//getting specific key values
Log.d("phonetype = ", jsonObject.getString("phonetype"));
Log.d("cat = ", jsonObject.getString("cat");
}catch (Exception ex) {
StringWriter stringWriter = new StringWriter();
ex.printStackTrace(new PrintWriter(stringWriter));
Log.e("exception ::: ", stringwriter.toString());
}
just try this ,
finally this works for me :
//delete backslashes ( \ ) :
data = data.replaceAll("[\\\\]{1}[\"]{1}","\"");
//delete first and last double quotation ( " ) :
data = data.substring(data.indexOf("{"),data.lastIndexOf("}")+1);
JSONObject json = new JSONObject(data);
To get a JSONObject or JSONArray from a String I've created this class:
public static class JSON {
public Object obj = null;
public boolean isJsonArray = false;
JSON(Object obj, boolean isJsonArray){
this.obj = obj;
this.isJsonArray = isJsonArray;
}
}
Here to get the JSON:
public static JSON fromStringToJSON(String jsonString){
boolean isJsonArray = false;
Object obj = null;
try {
JSONArray jsonArray = new JSONArray(jsonString);
Log.d("JSON", jsonArray.toString());
obj = jsonArray;
isJsonArray = true;
}
catch (Throwable t) {
Log.e("JSON", "Malformed JSON: \"" + jsonString + "\"");
}
if (object == null) {
try {
JSONObject jsonObject = new JSONObject(jsonString);
Log.d("JSON", jsonObject.toString());
obj = jsonObject;
isJsonArray = false;
} catch (Throwable t) {
Log.e("JSON", "Malformed JSON: \"" + jsonString + "\"");
}
}
return new JSON(obj, isJsonArray);
}
Example:
JSON json = fromStringToJSON("{\"message\":\"ciao\"}");
if (json.obj != null) {
// If the String is a JSON array
if (json.isJsonArray) {
JSONArray jsonArray = (JSONArray) json.obj;
}
// If it's a JSON object
else {
JSONObject jsonObject = (JSONObject) json.obj;
}
}
Using Kotlin
val data = "{\"ApiInfo\":{\"description\":\"userDetails\",\"status\":\"success\"},\"userDetails\":{\"Name\":\"somename\",\"userName\":\"value\"},\"pendingPushDetails\":[]}\n"
try {
val jsonObject = JSONObject(data)
val infoObj = jsonObject.getJSONObject("ApiInfo")
} catch (e: Exception) {
}
Here is the code, and you can decide which
(synchronized)StringBuffer or
faster StringBuilder to use.
Benchmark shows StringBuilder is Faster.
public class Main {
int times = 777;
long t;
{
StringBuffer sb = new StringBuffer();
t = System.currentTimeMillis();
for (int i = times; i --> 0 ;) {
sb.append("");
getJSONFromStringBuffer(String stringJSON);
}
System.out.println(System.currentTimeMillis() - t);
}
{
StringBuilder sb = new StringBuilder();
t = System.currentTimeMillis();
for (int i = times; i --> 0 ;) {
getJSONFromStringBUilder(String stringJSON);
sb.append("");
}
System.out.println(System.currentTimeMillis() - t);
}
private String getJSONFromStringBUilder(String stringJSONArray) throws JSONException {
return new StringBuffer(
new JSONArray(stringJSONArray).getJSONObject(0).getString("phonetype"))
.append(" ")
.append(
new JSONArray(employeeID).getJSONObject(0).getString("cat"))
.toString();
}
private String getJSONFromStringBuffer(String stringJSONArray) throws JSONException {
return new StringBuffer(
new JSONArray(stringJSONArray).getJSONObject(0).getString("phonetype"))
.append(" ")
.append(
new JSONArray(employeeID).getJSONObject(0).getString("cat"))
.toString();
}
}
May be below is better.
JSONObject jsonObject=null;
try {
jsonObject=new JSONObject();
jsonObject.put("phonetype","N95");
jsonObject.put("cat","wp");
String jsonStr=jsonObject.toString();
} catch (JSONException e) {
e.printStackTrace();
}

Categories

Resources