How to convert jsonstring to jsonobject in android? - java

i tried to convert jsonstring to json object. but its convert only first element.
here is my code
String d = [{"name":"kd","isMe":"yes","time":"10:12 AM"},{"name":"you","isMe":"no","time":"10:12 AM"}]
JSONObject j = new JSONObject(d);
its give following output
{"name":"kd","isMe":"yes","time":"10:12 AM"}
how can i convert this string into JSNOObject?

You can try like this, and your root is Json array not jsonobject
try {
JSONArray jsonArray = new JSONArray(d);
if(jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.optJSONObject(i);
if(jsonObject == null) {
continue;
}
String name = jsonObject.optString("name");
String isMe = jsonObject.optString("isMe");
String time = jsonObject.optString("time");
}
}
} catch (JSONException e) {
e.printStackTrace();
}

Use this
JSONObject jsonObject = new JSONObject(my_json_string);
JSONArray jresult = jsonObject.getJSONArray("array_in_the_json_string");

Related

Java jsonObject.get() returns null or an empty object for specific key [duplicate]

This question already has answers here:
Json object returning null against given key
(3 answers)
Closed 5 years ago.
Here's the JSON response.
The following works:
jsonObject.get("title").getAsString();
jsonObject.get("author").getAsJsonObject().get("profile_photo").getAsString();
but jsonObject.get("primary_photo").getAsString() (from line 60) returns an Unsupported Exception: null error. I've tried replacing getAsString() with toString() but the latter returns an empty string.
Try this
Use optJSONObject and optString in your code . And the root is [],so you should use JSONArray
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
// use optJSONObject
JSONObject author = jsonArray.optJSONObject(i).optJSONObject("author");
// use optString , it did not return null
String profile_photo = author.optString("profile_photo");
String primary_photo = jsonArray.optJSONObject(i).optString("primary_photo");
}
} catch (JSONException e) {
e.printStackTrace();
}
Gson
JsonArray jsonElements = new JsonParser().parse(response).getAsJsonArray();
for (int i = 0; i < jsonElements.size(); i++) {
JsonObject jObject = jsonElements.get(i).getAsJsonObject();
// edited here
String primary_photo = jObject.get("primary_photo").getAsString();
JsonObject author = jObject.getAsJsonObject("author");
String profile_photo = author.get("profile_photo").getAsString();
}
I think the Problem is, that your JSON response contains an Array. You have to create an JSONArray from the response-string and than iterate about it to get your values. Or if this array always contains one object:
JSONArray jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(0);
Try this,
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject author = jsonArray.get(i).getJSONObject"author");
String profile_photo = author.getString("author");
}
} catch (JSONException e) {
e.printStackTrace();
}
Try this:
try {
JSONArray jarr=new JSONArray(response); // response is whole json response
for (int i=0;i<jarr.length();i++){
JSONObject jobj=jarr.getJSONObject(i);
String primary_photo=jobj.getString("primary_photo");
}
} catch (JSONException e) {
e.printStackTrace();
}

Parsing another JSON Format

So here's the following code :
jObj = new JSONObject(valeurARenvoyer);
hauteur = jObj.getString("niveauEau");
debit = jObj.getString("debit");
date = jObj.getString("dateReleve");
batterie = jObj.getString("chargeBatterie");
presence = jObj.getString("etatPerimetrique");
bat = jObj.getString("chargeBatterie");
So i used this code to parse a JSON which was like that :
{"id":"15","id_Station":"Artiguelouve","Date_Releve":"2017-02-16 16:07:41","Niveau_Eau":"29","Charge_Batterie":"9","Etat_Perimetrique":"0","Debit":"13.35"}
It worked well, but now my JSON response looks like that :
{"Station":"Artiguelouve","debit":[{"niveauEau":0,"debit":32.5,"dateReleve":{"date":"2017-06-08 15:59:03","timezone_type":3,"timezone":"Europe\/Paris"},"idStation":"Artiguelouve","etatPerimetrique":true,"chargeBatterie":14590}]}
With this response i can't find how to parse this.
valeurARenvoyer is my JSON. Can you have any solution to do that please ?
add this code to get response
JSONObject jsonObject = new JSONObject(jsonResponse);//put your json response
JSONArray jsonArray = null;
try {
String station = jsonObject.getString("Station");
jsonArray = jsonObject.getJSONArray("debit");
for(int i=0;i<jsonArray.length();i++)
{
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
int niveauEau = jsonObject1.getInt("niveauEau");
int debit = jsonObject1.getInt("debit");
String isStation = jsonObject1.getString("idStation");
boolean etatPerimetrique = jsonObject1.getBoolean("etatPerimetrique");
int chargeBatterie = jsonObject1.getInt("chargeBatterie");
JSONObject jsonObject2 = jsonObject1.getJSONObject("dateReleve");
String date = jsonObject2.getString("date");
int timezone_type = jsonObject2.getInt("timezone_type");
String timezone = jsonObject2.getString("timezone");
}
} catch (JSONException e) {
e.printStackTrace();
}
try this code
try {
JSONObject jsonObject = new JSONObject(valeurARenvoyer);
JSONArray jsonArray = jsonObject.getJSONArray("debit");
for(int i = 0; i < jsonArray.length(); i++){
// you can get niveauEau, debit, idStation, etatPerimetrique,
// chargeBatterie, dateReleve JsonObject values in this loop
}
} catch (JSONException e) {
e.printStackTrace();
}

Trouble extracting values from JSON object in Java

Okay, I'm struggling here. I am getting the following JSON formated string from my php server (called "result") (edited! I was missing a curly brace at the end):
{"L1":[{"UserName":"User1","Avatar":"1"},{"UserName":"User2","Avatar":"2"},{"UserName":"User3","Avatar":"3"}],"L2":[{"UserName":"User4","Avatar":"4"},{"UserName":"User5","Avatar":"5"}]}
I'm trying to extract an ArrayList with the Avatar numbers from the L1 object(?). But I get an error
org.json.JSONException: Value
[{"UserName":"User1","Avatar":"1"},{"UserName":"User2","Avatar":"2"},{"UserName":"User3","Avatar":"3"}]
at L1 of type org.json.JSONArray cannot be converted to JSONObject
Here's my code:
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = new JSONArray(jsonObject.getJSONObject("L1"));
ArrayList<Integer> arrList = new ArrayList<>();
if (jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
arrList.add(json.getInt("Avatar"));
AvatarList = arrList;
}
}
String query_result = "SUCCESS";
if (query_result.equals("FAILURE")) {
} else {
setAvatars(AvatarList);
}
} catch (JSONException e) {
Log.e("log_tag", "Error converting result "+e.toString());
}
If I use
jsonObject.getJSONArray("L1")
I get the same error.
Any suggestions?
Thanks in advance!
(edit: I made a mistake in the original post. There was a missing curly brace in the JSON string. Thanks to those who caught that)
Try the below one.Its working fine. I'm using json-simple-1.1.1 jar
String r="{\"L1\":[{\"UserName\":\"User1\",\"Avatar\":\"1\"},{\"UserName\":\"User2\",\"Avatar\":\"2\"},{\"UserName\":\"User3\",\"Avatar\":\"3\"}],\"L2\":[{\"UserName\":\"User4\",\"Avatar\":\"4\"},{\"UserName\":\"User5\",\"Avatar\":\"5\"}]}";
Object obj=JSONValue.parse(r);
JSONObject jsonObject = (JSONObject) obj;
JSONArray jsonArray = (JSONArray) jsonObject.get("L1");
ArrayList<Integer> arrList = new ArrayList<>();
if (jsonArray != null) {
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject json = (JSONObject) jsonArray.get(i);
arrList.add((Integer.parseInt((String) json.get("Avatar"))));
AvatarList = arrList;
}
}
String query_result = "SUCCESS";
if (query_result.equals("FAILURE")) {
} else {
setAvatars(AvatarList);
}
This ended up working for me if anyone stumbles upon this. I don't really understand why this worked and my original method didn't... something to do with JSONObjects vs JSONArrays vs Strings and things like [, {, }, and ] probably.
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = new JSONArray(jsonObject.getString("L1"));
ArrayList<Integer> arrList = new ArrayList<>();
if (jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
arrList.add(json.getInt("Avatar"));
AvatarList = arrList;
}
}

JsonArray to List in Java

I have a problem with parsing JsonArray response.
I take JsonObject from JsonArray, parse it and set in entity message and then that message add to ArrayList.
Problem is that in ArrayList that I want to return I always have only one message. This must be some fundamental error but I cant find it.
public ArrayList<Message> getSearchInfo(String response) {
ArrayList<Message> searchResult = new ArrayList<Message>();
int jsonMessageId = -1;
String jsonDate = "";
String jsonText = "";
String jsonAutor = "";
String jsonSource = "";
int jsonThemeID = -1;
int jsonSourceID = -1;
try {
JSONArray jArray = new JSONArray(response);
if (jArray != null) {
for (int i = 0; i < jArray.length(); i++) {
try {
JSONObject oneObject = jArray.getJSONObject(i);
Message m = new Message();
// Pulling items from the array
jsonMessageId = oneObject.getInt("MessageId");
jsonDate = oneObject.getString("CreatedDate");
jsonText = oneObject.getString("TextMessage");
jsonAutor = oneObject.getString("Autor");
jsonSource = oneObject.getString("Source");
jsonThemeID = oneObject.getInt("ThemeId");
jsonSourceID = oneObject.getInt("SourceId");
m.setMessageId(jsonMessageId);
m.setMessageText(jsonText);
m.setDate(jsonDate);
m.setAutor(jsonAutor);
m.setSource(jsonSource);
m.setThemeId(jsonThemeID);
m.setSourceId(jsonSourceID);
searchResult.add(m);
} catch (JSONException e) {
Log.d("URL EXC", "Exception 2");
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return searchResult;
}
p.s. I use web-api as service and via android I take resources from service.
Any idea where is my mistake here?
You redefine your list every time in the loop.
Change your code from
JSONArray jArray = new JSONArray(response);
if (jArray != null) {
for (int i = 0; i < jArray.length(); i++) {
try {
searchResult = new ArrayList<Message>();
To
JSONArray jArray = new JSONArray(response);
if (jArray != null) {
searchResult = new ArrayList<Message>();
for (int i = 0; i < jArray.length(); i++) {
try {

Get JSON Array into strings.

I have a webservice which returns a JSON array in this format:
[{"imageid":"3","userid":"1","imagepath":"SLDFJNDSKJFN","filterid":"1","dateadded":"2014-05-06 21:20:18.920257","public":"t"},
{"imageid":"4","userid":"1","imagepath":"dsfkjsdkfjnkjdfsn","filterid":"1","dateadded":"2014-05-06 21:43:37.642748","public":"t"}]
I need to get all the attributes seperately? How would I do this?
I know how to do it with JSONObject if there is just 1 thing being returned, but how does it work when multiple items are returned?
Thanks
try {
JSONArray jArray = new JSONArray(jsonString);
String s = new String();
for (int i = 0; i < jArray.length(); i++) {
s = jArray.getJSONObject(i).getString("imageid").toString();
s = jArray.getJSONObject(i).getString("userid").toString();
}
} catch (JSONException je) {
}
Create an Object class with all variables, create a List for this Object, add all objects in your JSONArray to the list, use the one you need.
List<YourObject> objList = new ArrayList<YourObject>();
JSONArray a = new JSONArray(response);
int size = a.length();
for (int i=0 ; i<size ; i++){
JSONObject aa = a.getJSONObject(i);
String id = aa.getString("imageid");
String userid = aa.getString("userid");
String imagepath = aa.getString("imagepath");
String filterid = aa.getString("filterid");
String dateadded = aa.getString("dateadded");
String publicText = aa.getString("public");
YourObject obj = new YourObject(id,userid,imagepath,filterid,dateadded,publicText);
objList.add(obj);
}
So what you are having here is some JSON objects inside a JSON array.
What you want to do is this:
JSONArray array = ...;
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
// Extract whatever you want from the JSON object.
}
I hope it helped.
You can use JSONArray to parse array of JSON response.
private void parseJsonArray(String response) {
try {
JSONArray array = new JSONArray(response);
for(int i=0;i<array.length();i++){
JSONObject jsonObject = array.getJSONObject(i);
String ImageId = jsonObject.getString("imageid");
Log.v("JSON Parser", "ImageId: "+ImageId);
}
} catch (Exception e) {
e.printStackTrace();
}
}

Categories

Resources