JSONArray jsonArray = jo.getJSONArray("products_list");
productList = new ArrayList<>();
String ProductName = null;
String ProductQTY = null;
String ProductCost = null;
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject2 = jsonArray.getJSONObject(i);
ProductName = jsonObject2.getString("product_name");
ProductQTY = jsonObject2.getString("product_quantity");
ProductCost = jsonObject2.getString("product_cost");
}
Pname = ProductName;
Pqty = ProductQTY;
Pcost = ProductCost;
SaveProduct(BillNo, Pname, Pqty, Pcost);
and the corresponding json is-
"gstin_no": "987654321",
"products_list": [
{
"product_name": "himalaya shampoo",
"product_quantity": "20",
"product_cost": "100*product_quantity"
},
{
"product_name": "almonds",
"product_quantity": "2",
"product_cost": "400*product_quantity"
},
{
"product_name": "Rin Soap",
"product_quantity": "20",
"product_cost": "10*product_quantity"
},
{
"product_name": "himalaya shampoo",
"product_quantity": "20",
"product_cost": "100*product_quantity"
}]
I am trying to make an android app where i am scanning QR code and getting output in json format i want to send an array with multiple objects into Mysql database but when i am sending value to database i am value of last object is inserting in database . how can i insert all the objects of array into database??
How can I insert all the objects to the Mysql databse.
you are calling SaveProduct(BillNo, Pname, Pqty, Pcost);
after the for loop.so you are getting last index values.Make sure your method should be inside the loop.
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject2 = jsonArray.getJSONObject(i);
ProductName = jsonObject2.getString("product_name");
ProductQTY = jsonObject2.getString("product_quantity");
ProductCost = jsonObject2.getString("product_cost");
SaveProduct(BillNo, ProductName, ProductQTY, ProductCost);
}
So you need to make save call on your loop (json array length).
String BillNo = jo.optString("gstin_no");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject2 = jsonArray.optJSONObject(i);
String ProductName = jsonObject2.optString("product_name");
String ProductQTY = jsonObject2.optString("product_quantity");
String ProductCost = jsonObject2.optString("product_cost");
SaveProduct(BillNo, ProductName, ProductQTY, ProductCost);
}
I suggest Gson Library for better readable code
First, add this to your dependencies
implementation 'com.google.code.gson:gson:2.8.2
Second, create your product model class
public class Product {
private String product_name;
private String product_quantity;
private String product_cost;
}
just change your code with these lines
Gson gson = new Gson();
Type listType = new TypeToken<List<Product>>() {}.getType();
List<Product> productsList = new Gson().fromJson(jsonArray, listType);
then you can save productsList in database better code with a few lines and better performance
Related
json ImageI'm trying to extract a list (Array) of data out of a Json Object but i don't I don't know to. it's the value of "ingredients" i'm trying to extract. I have trying to extract it as a string but it comes out un-formatted. I have also provide a image of the raw jsonenter code here. if I try to extract it as 'cake.optJSONArray' I get a java.lang.ClassCastException: org.json.JSONArray cannot be cast to java.util.List
I have added more code to help the question make sense (fingers crossed I didn't make it more confusing).
try {
for (int i = 0; i < response.length(); i++) {
JSONObject cake = response.getJSONObject(i);
String cakeId = cake.optString("id");
String cakeName = cake.optString("name");
List<Ingredients> ingredients = (List<Ingredients>) cake.optJSONArray("ingredients");
mCakeList.add(new CakesItem(cakeId,ingredients, cakeName));
}
public class CakesItem {
private String mId;
private List<Ingredients> mIngredients;
private String mName;
public CakesItem(String cakeId, Lists <Ingrediets> ingredients String cakeName) {
mId = cakeId;
mIngredients = ingredients;
mName = cakeName;
}
public class Ingredients implements Parcelable {
private double quantity;
private String measure, ingredient;
public Ingredients() {
}
I'm not sure what JSON library you are using, but if you import org.json.JSONArray, then if your cake is a org.json.JSONObject that you got out of the JSONObject response returned from Volley, you would use this syntax:
JSONObject cake = response.getJSONObject(i);
JSONArray ingredients = cake.getJSONArray("ingredients");
Then, it is up to you to get the values out of the JSONArray ingredients into your List. It would look something like this:
for (int i = 0; i < response.length(); i++) {
JSONObject cake = response.getJSONObject(i);
String cakeId = cake.optString("id");
String cakeName = cake.optString("name");
JSONArray JSONingredients = cake.optJSONArray("ingredients");
List<Ingredients> ingredients = new List<Ingredients>();
for (int j = 0; j < JSONingredients.length(); j++) {
JSONObject item = JSONingredients.getObject(j);
String measure = item.getString(“measure”);
String ingredient = item.getString(“ingredient”);
Double quantity = item.getDouble(“quantity”);
Ingredients item2 = new Ingredients(measure, ingredient, quantity);
ingredients.add(item2);
}
mCakeList.add(new CakesItem(cakeId,ingredients, cakeName));
}
I have a json which has multiple values separated by commas which is in the
form of array.I want to get skills and platforms string separately.Can you please help me?
I want to show skills string and platforms string in text.
Please help me.
The format is:
{
"data": [
{
"skills": "ANDROID SDK, ANIMATION, ANGULARJS,",
"platforms": "IOS Application, Social Networking, Online shopping Sites, Web Application"
}
],
"status": 100
}
Try this one
try {
JSONObject ob = new JSONObject(response);
int status = ob.getInt("status");
if (status == 100) {
JSONArray ja = ob.getJSONArray("data");
for (int i = 0; i < ja.length(); i++) {
values = new HashMap<>();
JSONObject vj = ja.getJSONObject(i);
String skills = vj.getString("skills "));
String platforms=vj.getString("platforms"));
data.add(values);
}
split these 2 strings using 'split()'
List<String> skillsArray = Arrays.asList(skills.split(","));
List<String> platformsArray= Arrays.asList(platforms.split(","));
String in = "your json";
JSONObject jsonObj = new JSONObject(in);
// Getting JSON Array node
JSONArray jsonarray = jsonObj.getJSONArray("data");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String skills = jsonobject.getString("skills");
String platforms = jsonobject.getString("platforms");
}
Try this
JSONObject jsonObject = new JSONObject("Your json response");
JSONArray jsonArray = jsonObject.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonobject = jsonArray.getJSONObject(i);
String skill = jsonobject.getString("skills");
String platforms = jsonobject.getString("platforms");
String[] skillsArray = skill.split(Pattern.quote(","));
String[] platformsArray = platforms.split(Pattern.quote(","));
for (int j=0; j<skillsArray.length; j++)
{
Log.i("Skill Value ", "=" + skillsArray[j]);
}
for (int j=0; j<platformsArray.length; j++)
{
Log.i("platforms Value ", "=" + platformsArray[j]);
}
}
Output
First of all convert your output string into json. Note that output string is the string which contains your results of json format that you have posted above.following is the code on how to do that:
JSONObject myJsonResponse = new JSONObject(yourString);
The next one is Array. That is how you will get it and will iterate over it.
JSONArray jsonarray = jsonObj.getJSONArray("data");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject innerJsonObject= jsonarray.getJSONObject(i);
String skills = innerJsonObject.getString("skills");
String platforms = innerJsonObject.getString("platforms");
}
Now you have gotten your required fields and you can now perform any String functions over the String skills and platforms.
Happy coding. .
The best way is creating a model class such :
public class MyModel{
Properties [] data;
class Properties{
public String skills;
public String platforms;
}
}
then you can parse your string to model with Gson library like this :
MyModel myModel = new Gson().fromJson(yourString, MyModel.class)
so all data is in myModel object and you can access to skills with
myModel.data[0].skills
to add Gson library to your project add below to your app gradle file :
compile 'com.google.code.gson:gson:2.8.1'
You may try this,
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject("JSON_STRING");
JSONArray jsonArray = jsonObject.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonobject = jsonArray.getJSONObject(i);
String skills = jsonobject.getString("skills");
String[] seperateData = skills.split(Pattern.quote(","));
for (int j = 0; j < seperateData.length; j++) {
Log.e("Your Skill Value-> ", seperateData[j]);
}
String platforms = jsonobject.getString("platforms");
seperateData = platforms.split(Pattern.quote(","));
for (int j = 0; j < seperateData.length; j++) {
Log.e("Your Platform Value-> ", seperateData[j]);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
class Data{
public String skills;
public String platforms;
}
Gson gson = new Gson();
JSONArray dataArray = response.getJSONArray("data");
List<Data> dataList= gson.fromJson(dataArray toString(), new TypeToken<List<Data>>() {
}.getType());
Try this.. It will make parsing easier.
implementation 'com.google.code.gson:gson:2.8.0'
First Parse your JSON:
JSONObject jsonObj = new JSONObject(in);
JSONArray jsonarray = jsonObj.getJSONArray("data");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String skills = jsonobject.getString("skills");
String platforms = jsonobject.getString("platforms");
}
Then Split your string values:
String skills = "ANDROID SDK, ANIMATION, ANGULARJS";
String[] separated = CurrentString.split(",");
separated[0]; // this will contain "ANDROID SDK"
separated[1]; // this will contain " ANIMATION"
separated[2]; // this will contain " ANGULARJS"
You have to remove the space to the second String:
separated[1] = separated[1].trim();
Try this you will be getting all values of sapereted with commas
jsonString = getting string from server side
String[] separated = jsonString.split(",");
StringBuilder s = new StringBuilder(10000);
for (int i = 0; i < separated.length; i++) {
if (i == separated.length - 1) {
s.append(separated[i].trim() + "");
} else {
s.append(separated[i].trim() + ",\n");
}
}
//tvDisplayAddress.setText(s);
Log.e("VALUES: ",s+"");
i have a json file like so :
http://da.pantoto.org/api/files
i want to store these values in variables to be used later. The values should be stored in some String array variables like id[], uploadDate[], url[].
i can find examples using ListView and ArrayAdapter. but thats not what i really want. Anyone can help??
This is only an example to show how you can get the values from JSON. You need to store these values as you need.
JSONObject jsonObject = new JSONObject("your response");
JSONArray filedetails = jsonObject.getJSONArray("files");
for(int i=0; i<filedetails.size();i++){
String id = filedetails.get(i).getString("id");
JSONArray tagsdetails= filedetails.get(i).getJSONArray("tags");
for(int i=0; i<tagsdetails.size();i++){
//fetch values in it
}
}
You can't do it exactly that way, You have to iterate trough the array and get each object properties individually and then if you want you could create an array to store each object property.
//From the example: http://da.pantoto.org/api/files
JSONArray files = null;
//Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
//Making a request to url and getting response
String jsonStr = sh.makeServiceCall("http://da.pantoto.org/api/files", ServiceHandler.GET);
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
files = jsonObj.getJSONArray("files");
//YOUR NEW ARRAY
String[] ids = new String[20];
String[] urls = new String[20];
//etc
//looping through All files
for (int i = 0; i < files.length(); i++) {
JSONObject c = files.getJSONObject(i);
String id = c.getString("id");
String url = c.getString("url");
//etc
//HERE IS WHAT YOU COULD DO OPTIONALLY IF YOU WANT HAVE IT ALL ON A SINGLE ARRAY WITHOUT OBJECTS:
ids[i] = id;
urls[i] = url;
//etc
}
this is a simple way to do this. see i also done this kind of string array and later use
try {
JSONObject jObj = new JSONObject(strDocketListResponse);
JSONArray jsonArray = jObj.getJSONArray("GetManifestDocketListResult");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject detailsObject = jsonArray.getJSONObject(i);
String strDktNo = detailsObject.getString("Docketno");
String strDocketDate = detailsObject.getString("DocketDate");
String strOrigin = detailsObject.getString("Origin");
String strDestination = detailsObject.getString("Destination");
String[] strDocketNoDkt = new String[]{strDktNo};
String[] strDocketDateDkt = new String[]{strDocketDate};
String[] strDocketOriginDkt = new String[]{strOrigin};
String[] strDocketDestnDkt = new String[]{strDestination};
for (int sanjay = 0; sanjay < strDocketNoDkt.length; sanjay++) {
ItemCheckList itemCheckList = new ItemCheckList();
itemCheckList.setDocket_NO(strDocketNoDkt[sanjay]);
itemCheckList.setDocket_Date(strDocketDateDkt[sanjay]);
itemCheckList.setDocket_Origin(strDocketOriginDkt[sanjay]);
itemCheckList.setDocket_Destination(strDocketDestnDkt[sanjay]);
checkLists.add(itemCheckList);
}
checkAdapter = new ItemCheckAdapter(ActivityManifestEntry.this, checkLists, check_all);
manifestListView.setAdapter(checkAdapter);
}
} catch (Exception e) {
e.printStackTrace();
}
Here is my JSON:
{
"id": "11111",
"title": "title?",
"url": "www.example.com",
"fulltext": {
"page1": "<p>balblabba</p>",
"page2": "<p>avavaava</p>"
},
"related_articles": [
{
"id": "123",
"title": "title",
"image_name": "www.example.com/image1.png"
}
]
}
I need to put everything in Strings. I'm using this code:
String data = JSON TEXT!!!;
JSONObject jRealObject = new JSONObject(data);
String title = jRealObject.getString("title").toString();
String url = jRealObject.getString("url").toString();
String fulltext = jRealObject.getString("fulltext").toString();
String page1 = ????
String page2 = ????
jArray = jRealObject.getJSONArray("related_articles");
for (int i = 0; i < jArray.length(); i++) {
jRealObject = jArray.getJSONObject(i);
String relatedId = jRealObject.getString("id").toString();
String relatedTitle = jRealObject.getString("title").toString();
String relatedImage = jRealObject.getString("image_name").toString();
}
I'm getting everything, But I want to split "fultext" into two variables. but I don't know how can I get "page1" and "page2".
Here in your response "fulltext" is another Jsonobject use below code to get other data.
JSONObject fulltextobj = jRealObject.getJSONObject("fulltext");
String page1 = fulltextobj.getString("page1");
String page2 = fulltextobj.getString("page2");
JSONObject obj = jRealObject.getJSONObject("fulltext");
String var1 = obj.getString("page1");
String var2 = obj.getString("page2");
EDIT: You have a JSONObject nested into another JSONObject. fulltext is not a String, is a JSONObject indeed, so you have to get a JSONObject from parent
Try this way,hope this will help you to solve your problem.
try{
JSONObject jsonObject = new JSONObject("{\"id\":\"11111\",\"title\":\"title?\",\"url\":\"www.example.com\",\"fulltext\":{\"page1\":\"<p>balblabba</p>\",\"page2\":\"<p>avavaava</p>\"},\"related_articles\":[{\"id\":\"123\",\"title\":\"title\",\"image_name\":\"www.example.com/image1.png\"}]}");
HashMap<String,Object> responseMap = new HashMap<String, Object>();
ArrayList<HashMap<String,String>> articleList = new ArrayList<HashMap<String, String>>();
responseMap.put("id",jsonObject.getString("id"));
responseMap.put("title",jsonObject.getString("title"));
responseMap.put("url",jsonObject.getString("url"));
JSONObject fullTextJsonObject = jsonObject.getJSONObject("fulltext");
responseMap.put("page1",fullTextJsonObject.getString("page1"));
responseMap.put("page2",fullTextJsonObject.getString("page2"));
JSONArray relatedArticleJsonArray = jsonObject.getJSONArray("related_articles");
for(int i=0;i<relatedArticleJsonArray.length();i++){
HashMap<String,String> articleRow = new HashMap<String, String>();
articleRow.put("id", relatedArticleJsonArray.getJSONObject(i).getString("id"));
articleRow.put("title", relatedArticleJsonArray.getJSONObject(i).getString("title"));
articleRow.put("image_name", relatedArticleJsonArray.getJSONObject(i).getString("image_name"));
articleList.add(articleRow);
}
responseMap.put("related_articles",articleList);
System.out.print("id : "+responseMap.get("id").toString());
System.out.print("title : "+responseMap.get("title").toString());
System.out.print("url : "+responseMap.get("url").toString());
System.out.print("page1 : "+responseMap.get("page1").toString());
System.out.print("page2 : "+responseMap.get("page2").toString());
ArrayList<HashMap<String,String>> list = (ArrayList<HashMap<String,String>>)responseMap.get("related_articles");
for (HashMap<String,String> row : list){
System.out.print("id : "+row.get("id"));
System.out.print("title : "+row.get("title"));
System.out.print("image_name : "+row.get("image_name"));
}
}catch (Throwable e){
e.printStackTrace();
}
You are making string again toString which having no sense. please do some modification in your code .I have also done changes that you requrie.
String data = JSON TEXT!!!;
JSONObject jRealObject = new JSONObject(data);
String title = jRealObject.getString("title");
String url = jRealObject.getString("url");
String fulltext = jRealObject.getString("fulltext");
JSONObject obj = jRealObject.getJSONObject("fulltext");
String strPage1 = obj.getString("page1");
String strPage2 = obj.getString("page2");
jArray = jRealObject.getJSONArray("related_articles");
for (int i = 0; i < jArray.length(); i++) {
jRealObject = jArray.getJSONObject(i);
String relatedId = jRealObject.getString("id");
String relatedTitle = jRealObject.getString("title");
String relatedImage = jRealObject.getString("image_name");
}
how can parsing this output
{
"durum": "tamam",
"mahalleler": [
{
"mahalle_kodu": "1",
"mahalle_ismi": "BEKTAŞ MAH."
},
{
"mahalle_kodu": "2",
"mahalle_ismi": "ÇARŞI MAH."
}]}
i try this code but return "null".
contacts = json.getJSONArray("mahalleler");
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String name = c.getString("mahalle_kodu");
String body = c.getString("mahalle_ismi");}
what is the problem? json output has two variable; mahalleler[] and durum. i wanna parse durum's valur and values of mahalleler array. But i couldnt do that.
JSONObject json = new JSONObject("{
"durum": "tamam",
"mahalleler": [
{
"mahalle_kodu": "1",
"mahalle_ismi": "BEKTAŞ MAH."
},
{
"mahalle_kodu": "2",
"mahalle_ismi": "ÇARŞI MAH."
}]}
");
String name[]
String body[]
JSONArray contacts = json.getJSONArray("mahalleler");
name=new String[contacts.length()];
body =new String[contacts.length()];
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
name[i] = c.getString("mahalle_kodu");
body[i] = c.getString("mahalle_ismi");}
i think u r nt geting o/p as u declared the strings inside the for loop
You hve to do get json array like this
JSONArray mahallelerArray = c.getJSONArray("mahalleler");
you need to check if the content is in the json:
if (json != null && !json.isNull("mahalleler")) {
JSONArray contacts = json.getJSONArray("mahalleler");
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String name = c.getString("mahalle_kodu");
String body = c.getString("mahalle_ismi");}
}
You are declaring your String inside your for loop. Make them class variables arrays to store the data.