How to convert JSONObject to Hashmap? - android

String jsonString = "{"name":"kd","isMe":"yes","time":"10:12 AM"},{"name":"you","isMe":"no","time":"10:12 AM"}";
JSONObject jValueObject = new JSONObject(jsonString);
Iterator<?> values = jValueObject.keys();
while(values.hasNext()){
String final_key = (String)values.next();
String final_value = jValueObject.getString(final_key);
if (final_value != "")
map.put(final_key, final_value);
if (!final_key.equals("")) {
sbkeys.append(final_key).append(',');
}
}
Log.e("Final_Map", String.valueOf(map));
itemList = sbkeys.toString();
Output : {name=kd,isMe=yes,time=10:12 AM}

Try this code:
HashMap map = new HashMap<String, String>();
Iterator<?> values = jValueObject.keys();
while(values.hasNext()) {
String final_key = (String)values.next();
String final_value = jValueObject.optString(final_key, "");
if (!final_value.equals(""))
map.put(final_key, final_value);
}
for (k : map.keySet()) {
Log.d("Final_Map", "map[" + key + "] : " + map.get(k));
}

this is a duplicate question,
please check these answers
Convert JSONObject to Map
use Jackson(http://jackson.codehaus.org/) from http://json.org/
HashMap<String,Object> result =
new ObjectMapper().readValue(<JSON_OBJECT>, HashMap.class);
or
You can use Gson() (com.google.gson) library if you find any difficulty using Jackson.
HashMap<String, Object> yourHashMap = new Gson().fromJson(yourJsonObject.toString(), HashMap.class);

First off, if its a json array that you need in the string then wrap your string in square brackets. (I'd expect you've escaped the double quotes as well).
String jsonString = "[{\"name\":\"kd\",\"isMe\":\"yes\",\"time\":\"10:12 AM\"},{\"name\":\"you\",\"isMe\":\"no\",\"time\":\"10:12 AM\"}]";
Now its a JSONArray and not a JSONObject. So to get a list of Maps,
JSONArray jValueArray = new JSONArray(jsonString);
List<Object> listOfMaps = jValueArray.toList();
System.out.println(listOfMaps);
Prints:
[{isMe=yes, name=kd, time=10:12 AM}, {isMe=no, name=you, time=10:12 AM}]

JSONObject jObject = new JSONObject(jsonString);
Iterator<?> keys = jObject.keys();
while (keys.hasNext()) {
map = new HashMap<String, String>();
sbkeys = new StringBuilder();
String key = (String) keys.next();
String value = jObject.getString(key);
try{
JSONObject jValueObject = new JSONObject(value);
Iterator<?> values = jValueObject.keys();
while (values.hasNext()) {
String final_key = (String) values.next();
String final_value = jValueObject.getString(final_key);
if (!final_value.equalsIgnoreCase("")) {
map.put(final_key, final_value);
sbkeys.append(final_key).append(',');
}
}
}catch (Exception e){
e.fillInStackTrace();
}
try {
//// Your Code..
} catch (Exception e) {
errorCode = "1";
}
}

Related

how can i store muliple rows in JsonArray?

The problem is that in first row data save normally but in second row or move on data redundant Like:
public void Save(){
String register;
JSONObject jsonObj;
JSONObject json;
JSONArray jsonTempArray = new JSONArray();
JSONObject jsonObject=new JSONObject();
JSONArray jsonArray=new JSONArray();
try{
JSONObject jsonObjs=new JSONObject();
jsonObj=new JSONObject();
json=new JSONObject();
Integer.valueOf(mGeneralID);
str_UpdatedGeneralID= "6832";
String str_FMeasurementSamplesize = "";
if (txtFMeasurementSamplesize.getText().toString().equals("")){
str_FMeasurementSamplesize = "0";
}else {
str_FMeasurementSamplesize = txtFMeasurementSamplesize.getText().toString();
}
String Samplesize = txt_Sample_Size.getText().toString();
String Qtypersize = txt_Qty_per_Size.getText().toString();
String TotalnoofmeasPointsizeA = txtTotalnoOfmeasPointsizeA.getText().toString();
String TotalnoofmeasPointsizeAA = txtTotalnoOfmeasPointsizeAA.getText().toString();
String TotalnoofmeasPointsizeB = txtTotalnoOfmeasPointsizeB.getText().toString();
String TotalnoofmeasPointsizeBB = txtTotalnoOfmeasPointsizeBB.getText().toString();
String NomeasurementptoutoftolA = txtNomeasurementptoutoftolA.getText().toString();
String NomeasurementptoutoftolB = txtNomeasurementptoutoftolB.getText().toString();
String PASS = txt_pass.getText().toString();
String Fail = txt_fail.getText().toString();
String Pending = txt_pending.getText().toString();
String Remarks = txt_Remarks_F.getText().toString();
DateFormat df = new SimpleDateFormat("YYYY-MM-DD hh:mm:ss");
String CreationDate = df.format(Calendar.getInstance().getTime());
int a =0;
for (int i=0; i < MeasurementArrayList.size(); i++){
String MeasurementSheetDetailID = MeasurementArrayList.get(i).getmeasurementSheetDetailID();
String MeasurementPointID = MeasurementArrayList.get(i).getmeasurementPointID();
String MeasurementPoints = MeasurementArrayList.get(i).getmeasurementPoints();
String SpecSizeA = MeasurementArrayList.get(i).getSpecSizeA();
String SpecSizeAOne = MeasurementArrayList.get(i).getSpecSizeAOne();
String SpecSizeATwo = MeasurementArrayList.get(i).getSpecSizeATwo();
String SpecSizeAThree = MeasurementArrayList.get(i).getSpecSizeAThree();
String SpecSizeAFour = MeasurementArrayList.get(i).getSpecSizeAFour();
String SpecSizeAFive = MeasurementArrayList.get(i).getSpecSizeAFive();
String SpecSizeB = MeasurementArrayList.get(i).getSpecSizeB();
String SpecSizeBOne = MeasurementArrayList.get(i).getSpecSizeBOne();
String SpecSizeBTwo = MeasurementArrayList.get(i).getSpecSizeBTwo();
String SpecSizeBThree = MeasurementArrayList.get(i).getSpecSizeBThree();
String SpecSizeBFour = MeasurementArrayList.get(i).getSpecSizeBFour();
String SpecSizeBFive = MeasurementArrayList.get(i).getSpecSizeBFive();
String Tolerance = MeasurementArrayList.get(i).gettolerance();
jsonObj.put("MeasurementSheetID", str_FMeasurementSamplesize);
jsonObj.put("GeneralID", str_UpdatedGeneralID);
jsonObj.put("Samplesize", Samplesize);
jsonObj.put("Measurement", str_sp_Measurement);
jsonObj.put("Qtypersize", Qtypersize);
jsonObj.put("Color", str_sp_Color);
jsonObj.put("SpecSizeA", str_sp_SpecSizeA);
jsonObj.put("SpecSizeB", str_sp_SpecSizeB);
jsonObj.put("TotalnoofmeasPointsizeA",TotalnoofmeasPointsizeA);
jsonObj.put("TotalnoofmeasPointsizeAA", TotalnoofmeasPointsizeAA);
jsonObj.put("TotalnoofmeasPointsizeB", TotalnoofmeasPointsizeB);
jsonObj.put("TotalnoofmeasPointsizeBB", TotalnoofmeasPointsizeBB);
jsonObj.put("NomeasurementptoutoftolA", NomeasurementptoutoftolA);
jsonObj.put("NomeasurementptoutoftolB", NomeasurementptoutoftolB);
jsonObj.put("PASS", PASS);
jsonObj.put("Fail", Fail);
jsonObj.put("Pending", Pending);
jsonObj.put("Remarks", Remarks);
jsonObj.put("CreationDate", CreationDate);
jsonObj.put("MeasurementSheetDetailID", MeasurementSheetDetailID);
jsonObj.put("MeasurementPointID", MeasurementPointID);
jsonObj.put("MeasurementPoints", MeasurementPoints);
jsonObj.put("SpecSizeA", SpecSizeA);
jsonObj.put("SpecSizeAOne", SpecSizeAOne);
jsonObj.put("SpecSizeATwo", SpecSizeATwo);
jsonObj.put("SpecSizeAThree", SpecSizeAThree);
jsonObj.put("SpecSizeAFour", SpecSizeAFour);
jsonObj.put("SpecSizeAFive", SpecSizeAFive);
jsonObj.put("SpecSizeB", SpecSizeB);
jsonObj.put("SpecSizeBOne", SpecSizeBOne);
jsonObj.put("SpecSizeBTwo", SpecSizeBTwo);
jsonObj.put("SpecSizeBThree", SpecSizeBThree);
jsonObj.put("SpecSizeBFour", SpecSizeBFour);
jsonObj.put("SpecSizeBFive", SpecSizeBFive);
jsonObj.put("Tolerance", Tolerance);
jsonTempArray.put(jsonObj);
}
jsonObject.put("jsondata",jsonTempArray);
register=jsonObject.toString();
} catch (JSONException e) {
e.printStackTrace();
return;
}
new save(register).execute();
}
Result: Both rows are same that`s the problem
Row 1
[{"MeasurementSheetID":"0","GeneralID":"6832","Samplesize":"10","Measurement":"INCH","Qtypersize":"5","Color":"Black","SpecSizeA":"6.5","SpecSizeB":"6.5","TotalnoofmeasPointsizeA":"30","TotalnoofmeasPointsizeAA":"125","TotalnoofmeasPointsizeB":"30","TotalnoofmeasPointsizeBB":"125","NomeasurementptoutoftolA":"0","NomeasurementptoutoftolB":"0","PASS":"d","Fail":"h","Pending":"k","Remarks":"g","CreationDate":"2018-11-305
05:04:28","MeasurementSheetDetailID":"0","MeasurementPointID":"2","MeasurementPoints":"BACK
POCKET POSITION POSITION OUTER
EDGE","SpecSizeAOne":"","SpecSizeATwo":"","SpecSizeAThree":"","SpecSizeAFour":"","SpecSizeAFive":"","SpecSizeBOne":"","SpecSizeBTwo":"","SpecSizeBThree":"","SpecSizeBFour":"","SpecSizeBFive":"","Tolerance":"+/-0.5"},
Row 2
{"MeasurementSheetID":"0","GeneralID":"6832","Samplesize":"10","Measurement":"INCH","Qtypersize":"5","Color":"Black","SpecSizeA":"6.5","SpecSizeB":"6.5","TotalnoofmeasPointsizeA":"30","TotalnoofmeasPointsizeAA":"125","TotalnoofmeasPointsizeB":"30","TotalnoofmeasPointsizeBB":"125","NomeasurementptoutoftolA":"0","NomeasurementptoutoftolB":"0","PASS":"d","Fail":"h","Pending":"k","Remarks":"g","CreationDate":"2018-11-305
05:04:28","MeasurementSheetDetailID":"0","MeasurementPointID":"2","MeasurementPoints":"BACK
POCKET POSITION POSITION OUTER
EDGE","SpecSizeAOne":"","SpecSizeATwo":"","SpecSizeAThree":"","SpecSizeAFour":"","SpecSizeAFive":"","SpecSizeBOne":"","SpecSizeBTwo":"","SpecSizeBThree":"","SpecSizeBFour":"","SpecSizeBFive":"","Tolerance":"+/-0.5"}]
You need to put this jsonObj=new JSONObject(); inside your loop.
So every time loop execute it will create new JSONObject and put it into JSONArray
JsonArray is composed by jsonObjects.
You need to empty jsonobject, populate it and put in jsonarray for every object in jsonArray.
jsonObj = new JSONObject();
Some documentation

Convert JSON object string into integer

I want to change the string value of latitude into integer which i want to use in map location determination.
My code is as below:
try {
JSONObject jsonObj = new JSONObject(myJSON);
peoples = jsonObj.getJSONArray(TAG_RESULTS);
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String timedate = c.getString(TAG_TIMEDATE);
String binno = c.getString(TAG_BINNO);
String data1 = c.getString(TAG_DATA1);
String data2 = c.getString(TAG_DATA2);
String data3 = c.getString(TAG_DATA3);
String averagedata = c.getString(TAG_AVERAGEDATA);
String latitude = c.getString(TAG_LATITUDE);
String longitude = c.getString(TAG_LONGITUDE);
HashMap<String,String> trashcan = new HashMap<String,String>();
trashcan.put(TAG_TIMEDATE,timedate);
trashcan.put(TAG_BINNO,binno);
trashcan.put(TAG_DATA1,data1);
trashcan.put(TAG_DATA2,data2);
trashcan.put(TAG_DATA3,data3);
trashcan.put(TAG_AVERAGEDATA,averagedata);
trashcan.put(TAG_LATITUDE,latitude);
trashcan.put(TAG_LONGITUDE,longitude);
trashcanList.add(trashcan);
}
ListAdapter adapter = new SimpleAdapter(
MapsActivity.this, trashcanList, R.layout.list_item,
new String[]{TAG_TIMEDATE,TAG_BINNO,TAG_DATA1,TAG_DATA2,TAG_DATA3,TAG_AVERAGEDATA,TAG_LATITUDE,TAG_LONGITUDE},
new int[]{R.id.timedate,R.id.binno, R.id.data1,R.id.data2,R.id.data3,R.id.averagedata, R.id.latitude, R.id.longitude}
);
list.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
I have tried the following solutions but the value of latitude comes out to be zero everytime.
int latitude1 = jsonObj.getInt("Latitude");
The value of Lat and Lng should be something like
"lat" : 22.3361462197085,
"lng" : 114.1725279197085
You cannot put them in primitive int or Integer. You may want to use another data type like
String myJSON = "{\"lat\":\"22.3361462197085\",\"lng\":\"114.1725279197085\"}";
try {
JSONObject jsonObj = new JSONObject(myJSON);
BigDecimal lat = jsonObj.getBigDecimal("lat");
BigDecimal lng = jsonObj.getBigDecimal("lng");
System.out.println(lat);
System.out.println(lng);
} catch (JSONException e) {
e.printStackTrace();
}
If you cannot find getBigDecimal() method, try getDouble(String name) or getLong(String name).

Get JSONObject - Android

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 to set json data to list view?

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

Convert JSON key value pairs into JSON Array Android

I have an array of key-value pairs like this:
{
"320x240":"http:\/\/static.example.com\/media\/content\/2012\/Jul\/mercedes-benz-a-klasse-red-t_320x240.jpg",
"300x225":"http:\/\/static.zigwheels.com\/media\/content\/2012\/Jul\/mercedes-benz-a-klasse-red-t_300x225.jpg",
"200x150":"http:\/\/static.zigwheels.com\/media\/content\/2012\/Jul\/mercedes-benz-a-klasse-red-t_200x150.jpg"
}
What I'm doing currently is this:
try {
images_object = new JSONObject(imageList);//imageList is a String of the above array //of key value pairs
Iterator<?> keys = images_object.keys();
String string_images = "";
if(keys.hasNext()) {
String key = (String)keys.next();
String value = (String)images_object.get(key);
string_images = "[" + value;
}
while( keys.hasNext() ){
String key = (String)keys.next();
String value = (String)images_object.get(key);
string_images = string_images + "," + value;
}
string_images = string_images + "]";
String encoded_json_string = JSONObject.quote(string_images);
images = new JSONArray(encoded_json_string);//images is of type JSONArray but it is null
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
But, images, is NULL. Why's that? What am I missing?
you can get all values from current JSONObject in JSONArray as:
Iterator<String> keys = images_object.keys();
JSONArray images = new JSONArray();
while( keys.hasNext() ){
String key = keys.next();
String value = images_object.optString(key);
//add value to JSONArray from JSONObject
images.put(value);
}
EDIT
Simplified solution is get the keys with images_object.names() and you can pass JSONArray of keys to toJSONArray method to get the value with respect to keys in JSONArray
JSONArray keys=images_object.names();
JSONArray values=images_object.toJSONArray(keys);
To Summing up simplified solution is:
JSONArray images=images_object.toJSONArray(images_object.names());

Categories

Resources