Test the number of json object - android

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

Related

Json move to next item

I have a dynamic JSON string that looks like this:
{"_id":"7","food_name":"Fiber Balance"},{"_id":"8","food_name":"Sport +"}
I am able to get the first name, but not the second one. This is my code for getting the first (Fiber Balance):
// Dynamic text
TextView textViewDynamicText = (TextView)getActivity().findViewById(R.id.textViewDynamicText);
String stringJSON = textViewDynamicText.getText().toString();
String stringFoodname = "";
try {
JSONObject jsonObject = new JSONObject(stringJSON);
Iterator<String> iter = jsonObject.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
stringFoodname = jsonObject.getString("food_name");
Toast.makeText(getContext(), stringFoodname, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
// Something went wrong!
}
}
} catch (org.json.JSONException e) {
// Something went wrong!
}
How can I go to the next item in the json string?
If you have multiple data than you need to use Array,if you want to get all data from your json use below trick,
String json = "{\"_id\":\"7\",\"food_name\":\"Fiber Balance\"},{\"_id\":\"8\",\"food_name\":\"Sport +\"}";
json = "[" + json + "]";
try {
JSONArray array = new JSONArray(json);
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
String foodName = object.getString("food_name");
Log.e("FoodName:", foodName);
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("error", "json", e);
}

how can decode json data form api in android?

I am geting JSON data getting from web service. Below is my code.
How can I decode the json data?
{
"response": [
{
"last_name": "Test",
"id": 279711390,
"first_name": "Vishnu",
"sex": 2,
"photo_50": "https://vk.com/images/camera_50.gif"
}
]
}
How can I parse it? Thanks.
You can keep a POJO class. With the data which you are about to get from server. And parse them and save in that object.
Example:
JSONObject json= new JSONObject(responseString); //your response
try {
JSONArray responseArray = jsonObj.getJSONArray("response");
for (int i = 0; i < responseArray.length(); i++) {
// get value with the NODE key
JSONObject obj = responseArray.getJSONObject(i);
String lastName = obj.getString("last_name");
String firstName = obj.getString("first_name");
//same for all other fields in responseArray
MyResponse myResp = new MyResponse();
myResp.setFirstName(firstName);
myResp.setLastName(lastName);
//set all other Strings
//lastly add this object to ArrayList<MyResponse> So you can access all data after saving
}
}
catch (JSONException e) {
e.printStackTrace();
}
POJO Class:
public class MyResponse{
public String firstName="";
public String lastName="";
//all other fields and getter setters
}
Hope this helps.
You can parse JSON using this code:
str="<The Json>"
try {
JSONObject jObject=new JSONObject(str);
JSONArray menuObject = new JSONArray(jObject.getString("response"));
String lastName;
for (int i = 0; i<menuObject.length(); i++) {
lastName=menuObject.getJSONObject(i).getString("last_name").toString();
...
}
catch (JSONException e) {
e.printStackTrace();
}
Use this code :-
String string = "Your Json"
try {
JSONObject jsonObject=new JSONObject(str);
JSONArray menuObject = new JSONArray(jObject.getJsonArray("response"));
//no need of for loop because you have only one object in jsonArray.
JSONObject oject = menuObject.getJSONObject(0);
String lastName = object.getString("last_name");
String firstName = object.getString("first_name");
Log.d("User Name", firstName + " " + lastName);
catch (JSONException e) {
e.printStackTrace();
}

jsonobject cannot be converted with multiple input possibilities

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;
}

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();
}

Accessing json contents in android [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Sending and Parsing JSON in Android
I have a JSON result in the following format which JSON Lint shows this as a Valid Response.
My question is: how do I accesss the content of "reportId0" value "164", "reportId1" value 157,reportId2 value 165, etc are all dynamic values?
My sample code for accessing value of properties.How to get Value reportid And add allvalue in Arraylist?
"properties": {
"link": "",
"approvalsReportCount": 3,
"reportName0": "srcapprovals",
"reportId0": 164,
"reportName1": "Approvals",
"reportId1": 157,
"requests_report_id": "163",
"requests_report_name": "EG approvals",
"reportName2": "fulfillment",
"reportId2": 165
}
This is the best way i found it to get ReportId value.
Below is My code
JSONObject jObj = new JSONObject(result);
JSONObject jsonResultArray = jObj.getJSONObject("results");
JSONObject pro_object = jsonResultArray.getJSONObject("properties");
Iterator keys = pro_object.keys();
while(keys.hasNext()) {
String currentDynamicKey = (String)keys.next();
String value = pro_object.getString(currentDynamicKey);
String upToEightCharacters = currentDynamicKey.substring(0, Math.min(currentDynamicKey.length(), 8));
if(upToEightCharacters.startsWith("reportId"))
{
Log.v("key"," new report ID key " + currentDynamicKey);
Log.v("key"," new report ID key " + pro_object.getString(currentDynamicKey) );
}
}
you can use this
public ArrayList<String> getReportIds() {
boolean isContinue = true;
JSONObject json;
String tag = "reportId";
int i = 0;
ArrayList<String> repIdList = new ArrayList<String>();
JSONObject prop = null;
try {
json = new JSONObject("<your json string>");
prop = json.getJSONObject("properties");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while (isContinue) {
String repId = "";
try {
repId = prop.getString(tag + i);
repIdList.add(repId);
i++;
} catch (JSONException e) {
isContinue = false;
e.printStackTrace();
}
}
return repIdList;
}
You can Try This!!
try {
JSONObject jObj = new JSONObject(result);
JSONObject jsonResultArray = jObj.getJSONObject("results");
Log.v("log_tag","json result Array : "+ jsonResultArray);
JSONObject pro_object = jsonResultArray.getJSONObject("properties");
Iterator keys = pro_object.keys();
while(keys.hasNext()) {
// loop to get the dynamic key
String currentDynamicKey = (String)keys.next();
String value = pro_object.getString(currentDynamicKey);
approvaldto_Key = new All_Approval_Key_dto();
String upToEightCharacters = currentDynamicKey.substring(0, Math.min(currentDynamicKey.length(), 8));
if(upToEightCharacters.startsWith("reportId"))
{
approvaldto_Key.requestId = pro_object.getString(currentDynamicKey);
fetchrecursUserData.add(approvaldto_Key);
}
}
}
catch (JSONException e) {
e.printStackTrace();
}
return fetchrecursUserData;
}
You can try below code
String serial= jsonObject.getJSONObject("response").getString("serialNumber");
or
JSONObject json;
try {
json = new JSONObject(buffer.toString());
String accessToken = json.getString("access_token");
return accessToken;
} catch (JSONException e) {
Log.e("Podcast", "There was an error", e);
}

Categories

Resources