This is my codes :
JSONObject jsonObject = new JSONObject(response.toString());
JSONObject jsonOb=jsonObject.getJSONObject("LocationMatrix");
Log.e(TAG,"jsonOb :"+jsonOb.toString());
Then print out :
jsonOb :{"45":"NUMANCIA 39-41","44":"DEMESTRE 10","35":"ALIÓ 19","22":"ALFONSO X EL SABIO 8","36":"ROSARI 42","23":"PI I MARGALL 101","33":"MELCHOR DE PALAU 65","24":"ROBRENYO, ESC.A 55","34":"SARDENYA 545","25":"ROBRENYO, ESC.B 55","39":"L´ERAMPPRUNYA 41","26":"ROSSELLO 230","27":" ENRIQUE GIMENEZ 10","37":"CALATRAVA 1-7 E","28":"GRAN VIA CORTS CATALANES 489","38":"AUGUSTA 276","29":"AUTOVIA DE CASTELLDEFELS 135","43":"ROSARIO 37","30":"GANDUXER 72","42":"VALLDEMOSA 64","41":"VALLDEMOSA 62","32":"CONSELL DE CENT 97","40":"VALLDEMOSA 60","31":"SANTA AMELIA 22"}
How to make custom ArrayList using JsonObject values?
For Example :
for (int i = 0; i < jsonOb.length(); i++) {
int mId = intValue;
String mTitle = StringValue;
locationList.add(new Location(mId, mTitle));
}
Where LocationList is one kind of custome ArrayList<Location>.
and Location is one kind of class which parameters id, title.
use gson library
How To Convert Java Object To / From JSON (Gson)
POJO
package com.mkyong.core;
import java.util.ArrayList;
import java.util.List;
public class DataObject {
private int data1 = 100;
private String data2 = "hello";
private List<String> list = new ArrayList<String>() {
{
add("String 1");
add("String 2");
add("String 3");
}
};
//getter and setter methods
#Override
public String toString() {
return "DataObject [data1=" + data1 + ", data2=" + data2 + ", list="
+ list + "]";
}
}
JSON STRING
{"data1":100,"data2":"hello","list":["String 1","String 2","String 3"]}
DataObject obj = gson.fromJson(str, DataObject.class);
link
Try this..
JSONObject jsonObject = new JSONObject(response.toString());
JSONObject jsonOb=jsonObject.getJSONObject("LocationMatrix");
Log.e(TAG,"jsonOb :"+jsonOb.toString());
Iterator i = jsonOb.keys();
while (i.hasNext()) {
try {
String key = i.next().toString();
String j = jsonOb.getString(key);
locationList.add(new Location(Integer.parseInt(key), j));
} catch (JSONException e) {
e.printStackTrace();
}
}
Related
I am getting null pointer error while converting string to json object i have tried gson,parser etc but none seems to be working.
Can somebody provide a solution for below response (I have done substring in order to remove "data: "):
data: {
"C": "abc",
"A": [{
"B": "BcastHub",
"C": "onData",
"D": [{
"ID": "1",
"One": [{
"Plus": 5.0,
"Minus": 93400.0
}, {
"Plus": 4.9,
"Minus": 8570.0
}, {
"Plus": 4.8,
"Minus": 140606.0
}],
"Two": [{
"Plus": 5.1,
"Minus": 34.0
}, {
"Plus": 5.2,
"Minus": 44622.0
}, {
"Plus": 5.3,
"Minus": 2408.0
}]
}]
}]
}
My code for Fetching
try{
URL urlData = new URL(url);
BufferedReader reader = new BufferedReader(new InputStreamReader(
urlData.openConnection().getInputStream(), "utf-8"));
String struct = reader.readLine();
while ((struct = reader.readLine()) != null ) {
if(!struct.equals("")) {
struct = struct.substring(6,struct.length());
JSONParser parser = new JSONParser();
JSONObject lev1 =(JSONObject) parser.parse(struct);
//JSONObject lev1 = (JSONObject) obj;
JSONObject parent = (JSONObject) lev1.get("A");
for(int j=0;j<parent.length();j++) {
JSONObject child1 = (JSONObject) parent.get("D");
JSONArray child2 = (JSONArray) child1.get("One");
for (int i = 0; i < child2.length(); i++) {
JSONObject item = child2.getJSONObject(i);
final String plus = item.getString("Plus");
final String minus = item.getString("Minus");
runOnUiThread(new Runnable() {
#Override
public void run() {
tv.setText("Plus => " + plus + "Minus = > " + minus);
}
});
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
Tell me if you want anything else. Thanks.
Edit : I am trimming the start of the string in order to make it in proper format and then converting the string to JSONObject is giving me error. at JSONObject parent = (JSONObject) lev1.get("A"); as lev1 is null.
try {
jsonResponse = new JSONObject(strJson2);
JSONObject user = jsonResponse.getJSONObject("data");
num = user.getString("C");
JSONArray user1 = user.getJSONArray("A");
for (int i = 0; i < user1.length(); i++) {
jsonChildNode = user1.getJSONObject(i);
String B = jsonChildNode.getString("B");
String c2 = jsonChildNode.getString("C");
Toast.makeText(this, B + "::" + c2.toString(), Toast.LENGTH_SHORT).show();
JSONArray jsonArraysunject = jsonChildNode.getJSONArray("D");
for (int j = 0; j < jsonArraysunject.length(); j++) {
JSONObject DD = jsonArraysunject.getJSONObject(j);
String dd = DD.getString("ID");
Toast.makeText(this, dd.toString(), Toast.LENGTH_SHORT).show();
One = DD.getJSONArray("One");
for (int k = 0; k < One.length(); k++) {
// for (int i = 0; i < lengthJsonArr; i++) {
jsonChildNodeo = One.getJSONObject(k);
type = jsonChildNodeo.getString("Plus");
num = jsonChildNodeo.getString("Minus");
makeText.add("Plus - " + type);
makeText.add("Minus - " + num);
Toast.makeText(this, makeText.toString(), Toast.LENGTH_SHORT).show();
}
Toast.makeText(this, "hdjeh", Toast.LENGTH_SHORT).show();
Two = jsonChildNodeo.getJSONArray("Two");
Toast.makeText(this, Two.toString(), Toast.LENGTH_SHORT).show();
for (int r = 0; r < Two.length(); r++) {
JSONObject tw = Two.getJSONObject(r);
String tplus = tw.getString("Plus");
String tminus = tw.getString("Minus");
makeText2.add("plus - " + tplus);
makeText2.add("minus - " + tminus);
Toast.makeText(this, makeText2.toString(), Toast.LENGTH_SHORT).show();
// }
}
}
Just place your json data in jsonString vairable and that's all.
try {
JSONObject mainObject=new JSONObject(jsonString);
System.out.println(mainObject.toString());
System.out.println("// First Level object(s)");
System.out.println("C--> "+mainObject.getString("C"));// First Level object C
JSONArray firstArray=mainObject.getJSONArray("A");
for(int i=0;i<firstArray.length();i++){ //First Level Array A
JSONObject arrayObject =firstArray.getJSONObject(i);
System.out.println("// Second Level object(s)");
System.out.println("B--> "+arrayObject.getString("B")); // Second Level Object B
System.out.println("C--> "+arrayObject.getString("C")); // Second Level Object C
System.out.println("//Second Level Array D");
JSONArray secondLevelArray=arrayObject.getJSONArray("D");
for(int j=0;j<secondLevelArray.length();j++){
JSONObject innerArrayObject=secondLevelArray.getJSONObject(j);
System.out.println("// Third Level object(s) ");
System.out.println("ID --> "+innerArrayObject.getString("ID"));
JSONArray thirlLevelArray1=innerArrayObject.getJSONArray("One");
for(int k=0;k<thirlLevelArray1.length();k++){
JSONObject innerMostObjects=thirlLevelArray1.getJSONObject(k);
System.out.println("Plus -->"+innerMostObjects.get("Plus"));
System.out.println("Minus -->"+innerMostObjects.get("Minus"));
}
JSONArray thirlLevelArray2=innerArrayObject.getJSONArray("Two");
for(int k=0;k<thirlLevelArray2.length();k++){
JSONObject innerMostObjects=thirlLevelArray2.getJSONObject(k);
System.out.println("Plus -->"+innerMostObjects.get("Plus"));
System.out.println("Minus -->"+innerMostObjects.get("Minus"));
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
I parsed your data using Gson. The advantages of Gson are discussed previously. In addition, you can check goals of Gson.
Here is how to parse your data using Gson:
Note that I have not used code formatting standards (for example, the name of a class should use CamelCase) because you couldn't share real data.
Extracting JSON string:
While extracting JSON string use indexOf(int) instead of hard-coded 6.
jsonString = jsonString.substring(jsonString.indexOf("{"));
Parsing:
Gson gson = new Gson();
data d = gson.fromJson(reader, data.class);
for (a a1 : d.A) {
for (plusminus pm : a1.D[0].One) {
System.out.println("Plus => " + pm.Plus + " Minus => " + pm.Minus);
}
}
Required Classes:
public class data {
public String C;
public a A[];
}
public class a {
public String B;
public String C;
public d D[];
}
public class d {
public int ID;
public plusminus One[], Two[];
}
public class plusminus {
public double Plus;
public double Minus;
}
I am trying to parse a JSON array from a string which I receive from the server.
Example of the array is
{"data":[{"id":703,"status":0,"number":"123456","name":"Art"}]}
I am trying to parse that using the below code which is giving me Classcast Exception which shows JSonArray can not be cast to List
JSONObject o = new JSONObject(result.toString());
JSONArray slideContent = (JSONArray) o.get("data");
Iterator i = ((List<NameValuePair>) slideContent).iterator();
while (i.hasNext()) {
JSONObject slide = (JSONObject) i.next();
int title = (Integer)slide.get("id");
String Status = (String)slide.get("status");
String name = (String)slide.get("name");
String number = (String)slide.get("number");
Log.v("ONMESSAGE", title + " " + Status + " " + name + " " + number);
// System.out.println(title);
}
What should be the correct way of parsing it?
It makes sense as a JSONArray cannot be cast to a List<>, nor does it have an iterator.
JSONArray has a length() property which returns its length, and has several get(int index) methods which allow you to retrieve the element in that position.
So, considering all these, you may wish to write something like this:
JSONObject o = new JSONObject(result.toString());
JSONArray slideContent = o.getJSONArray("data");
for(int i = 0 ; i < slideContent.length() ; i++) {
int title = slideContent.getInt("id");
String Status = slideContent.getString("status");
// Get your other values here
}
you should do like this:
JSONObject o = new JSONObject(result.toString());
JSONArray array = jsonObject.getJSONArray("data");
JSONObject jtemp ;
ArrayList<MData/*a sample class to store data details*/> dataArray= new ArrayList<MData>();
MData mData;
for(int i=0;i<array.length();i++)
{
mData = new MData();
jtemp = array.getJSONObject(i); //get i record of your array
//do some thing with this like
String id = jtemp.getString("id");
mData.setId(Integer.parseInt(id));
///and other details
dataArray.put(mData);
}
and MData.class
class MData{
private int id;
/....
public void setId(int id){
this.id = id;
}
//.....
}
I tried to add json data to listview.But i don't know how to add the json data to list adapter.
try {
mylist = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jsonResponse = new JSONObject(strJson1);
JSONArray jsonMainNode = jsonResponse.optJSONArray("restaurants");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String restName = jsonChildNode.optString("name");
Toast.makeText(getApplicationContext(), name, Toast.LENGTH_LONG).show();
if(restName.equalsIgnoreCase(name)){//this name is predefined name.
String address = jsonChildNode.optString("address");
String mobile = jsonChildNode.optString("mobile");
String direction = "Direction: "+jsonChildNode.optString("direction");
String bestTime = "Best time to visite: "+jsonChildNode.optString("bestTime");
String food = jsonChildNode.optString("food");
String dress = jsonChildNode.optString("dress");
String priceRange = "Price Range: "+jsonChildNode.optString("priceRange");
String rate = jsonChildNode.optString("Rate");
String comment = "Price Range: "+jsonChildNode.optString("comment");
map.put("restName",restName);
map.put("address",address);
map.put("mobile",mobile);
map.put("direction",direction);
map.put("bestTime",bestTime);
map.put("food",food);
map.put("dress",dress);
map.put("priceRange",priceRange);
map.put("rate",rate);
map.put("comment",comment);
mylist = new ArrayList<HashMap<String, String>>();
mylist.add(map);
}else{
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG).show();
}
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error..." + e.toString(),
Toast.LENGTH_LONG).show();
}
// ListAdapter adapter = new SimpleAdapter(getApplicationContext(),android.R.layout.simple_list_item_1,mylist);
// list.setAdapter(adapter);
}
Can anyone tel me how to set this data to list view.?
Try this..
Your doing reversely. declear the arraylist before for loop and declear the HashMap inside the for loop .
mylist = new ArrayList<HashMap<String, String>>();
JSONObject jsonResponse = new JSONObject(strJson1);
JSONArray jsonMainNode = jsonResponse.optJSONArray("restaurants");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String restName = jsonChildNode.optString("name");
Toast.makeText(getApplicationContext(), name, Toast.LENGTH_LONG).show();
if(restName.equalsIgnoreCase(name)){//this name is predefined name.
HashMap<String, String> map = new HashMap<String, String>();
String address = jsonChildNode.optString("address");
//So on
map.put("restName",restName);
//So on
mylist.add(map);
}else{
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG).show();
}
google-gson
I would use gson for this. Check the gson project website for more details on how. This is an example for object serialisation/deserialisation:
Object Examples
class BagOfPrimitives {
private int value1 = 1;
private String value2 = "abc";
private transient int value3 = 3;
BagOfPrimitives() {
// no-args constructor
}
}
(Serialization)
BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj);
==> json is {"value1":1,"value2":"abc"}
Note that you can not serialize objects with circular references since that will result in infinite recursion.
(Deserialization)
BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);
==> obj2 is just like obj
write Custom ArrayAdapter by example: http://www.ezzylearning.com/tutorial.aspx?tid=1763429&q=customizing-android-listview-items-with-custom-arrayadapter
i can't fill array in cycle.
working example:
Weather weather_data[] = new Weather[]
{ new Weather("http://www.ezzylearning.com/images/ImagesNew/net_framework.png", "Cloudy"),
new Weather("http://www.ezzylearning.com/images/ImagesNew/net_framework.png", "Showers")
};
my code:
NewsData[] NewsData_data;
// build hash set for list view
public void ListDrwaer() {
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("news");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String header = jsonChildNode.optString("header");
String short_text = jsonChildNode.optString("short_text");
String team = jsonChildNode.optString("team");
String datatime = jsonChildNode.optString("datatime");
String photo_url = jsonChildNode.optString("photo_url");
NewsData_data[i] = new NewsData(header, short_text, team, datatime, photo_url);
}
} catch (JSONException e) {
Toast.makeText(getActivity(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
NewsDataAdapter adapter = new NewsDataAdapter(getActivity(),
R.layout.news_details, NewsData_data);
listView.setAdapter(adapter);
}
You need to initialize this array:
NewsData[] NewsData_data;
// build hash set for list view
public void ListDrwaer() {
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("news");
NewsData_data=new NewsData[jsonMainNode.length()];//<------------HERE
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String header = jsonChildNode.optString("header");
String short_text = jsonChildNode.optString("short_text");
String team = jsonChildNode.optString("team");
String datatime = jsonChildNode.optString("datatime");
String photo_url = jsonChildNode.optString("photo_url");
NewsData_data[i] = new NewsData(header, short_text, team, datatime, photo_url);
}
} catch (JSONException e) {
Toast.makeText(getActivity(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
NewsDataAdapter adapter = new NewsDataAdapter(getActivity(),
R.layout.news_details, NewsData_data);
listView.setAdapter(adapter);
}
Simplified answer: your array is not initialized. Longer answer, you have to know how big it is going to be, then initialize it to that size. A simple example:
NewsData[] NewsData_data;
ArrayList<NewsData> newsDataArray = new ArrayList<NewsData>();
String header = "header";
String short_text = "short_text";
String team = "team";
String datatime = "datatime";
String photo_url = "photo_url";
newsDataArray.add(new NewsData(header, short_text, team, datatime, photo_url));
newsDataArray.add(new NewsData(header, short_text, team, datatime, photo_url));
NewsData_data = new NewsData[newsDataArray.size()];
newsDataArray.toArray(NewsData_data);
System.out.println(NewsData_data);
In my web service I'm making a query to a database, and I would like to return 2 columns of the database and put these columns in a 2d array.
Also I would like to convert the array to JSON and send it to the client. The client using gson parses the message from the server in a 2d array. Is it possible?
I have tried a lot but no luck till now. Thank you in advance.
The last version i've tried is this:
private static String[][] db_load_mes (String u){
ArrayList<String> array1 = new ArrayList<String>();
ArrayList<String> array2 = new ArrayList<String>();
JSONObject messages = new JSONObject();
Connection c = null;
try{
// Load the driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
c = DriverManager.getConnection("jdbc:odbc:dsn1","mymsg","mymsg");
Statement s = c.createStatement();
// SQL code:
ResultSet r;
r = s.executeQuery("select * from accounts ");
int i = 0, j = 0;
int k = 0;
String x,y;
while(r.next()) {
x = r.getString("username");
array1.add(x);
y = r.getString("password");
array2.add(y);
k = k + 1;
}
int count = array1.size();
String[][] row = new String[count][2];
Iterator<String> iter = array1.iterator();
while (iter.hasNext()) {
row[i][0]=iter.next();
i++;
}
Iterator<String> iter2 = array2.iterator();
while (iter2.hasNext()) {
row[j][1]=iter2.next();
j++;
}
for(int z=0;z<count;z++)
System.out.println(row[z][0] + "\t" + row[z][1] + "\n");
if (k == 0)
System.err.println("no accounts!");
c.close();
s.close();
}
catch(SQLException se)
{
System.err.println(se);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return ...;
}
With the above code I can create the 2d array but how can I send this array to the client.
Here is how I made it using Gson from google...
Download gson from here
include it in your project.
package javaapplication1;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class JavaApplication1 {
public static void main(String[] args) {
int rows = 3;
String records[][] = new String[][]{{"bob", "123-pass"},
{"erika", "abc123"},
{"richard", "123123123"}
};
Gson gson = new Gson();
String recordsSerialized = gson.toJson(records);
System.out.println(recordsSerialized);
/* prints this
[["bob","123-pass"],["erika","abc123"],["richard","123123123"]]
*/
// if you want a better output import com.google.gson.GsonBuilder;
Gson gsonPretty = new GsonBuilder().setPrettyPrinting().create();
String recordsSerializedPretty = gsonPretty.toJson(records);
System.out.println(recordsSerializedPretty);
/* PRINTS IN different lines.. I can't paste it here */
// for retrieval
String retrievedArray[][] = gsonPretty.fromJson(recordsSerializedPretty, String[][].class);
for (int i = 0; i < retrievedArray.length; i++) {
for (int j = 0; j < retrievedArray[0].length; j++) {
System.out.print(retrievedArray[i][j]+" ");
}
System.out.println("");
}
// PRINTS THIS
/*
bob 123-pass
erika abc123
richard 123123123
*/
}
}