Covert JSON hashmap to Java hashmap - json

json = [{"a":"555","b":"ee"},{"a":"556","b":"rr"}]
I tried:
ObjectMapper mapper = new ObjectMapper();
TypeReference<Map<String,String>> typeRef = new TypeReference<Map<String,String>>() {};
HashMap<String, String> result = mapper.readValue(json, typeRef);
but it's not working. I suppose that's the reason is that json is a list and not a single object.
In fact, if json was {"a":"555","b":"ee"}, it works.

In order to solve the problem I'll use Jackson SDK.
Please download the latest version from: http://wiki.fasterxml.com/JacksonDownload
JSON TO MAP EXAMPLE:
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonMapExample {
public static void main(String[] args) {
try {
ObjectMapper mapper = new ObjectMapper();
String json = "{\"name\":\"mkyong\", \"age\":29}";
Map<String, Object> map = new HashMap<String, Object>();
// convert JSON string to Map
map = mapper.readValue(json, new TypeReference<Map<String, String>>(){});
System.out.println(map);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Map to JSON EXAMPLE:
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class MapJsonExample{
public static void main(String[] args) {
try {
ObjectMapper mapper = new ObjectMapper();
String json = "";
Map<String, Object> map = new HashMap<String, Object>();
map.put("name", "mkyong");
map.put("age", 29);
// convert map to JSON string
json = mapper.writeValueAsString(map);
System.out.println(json);
json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(map);
// pretty print
System.out.println(json);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
JSONArray to HashMaps:
HashMap<String, String> pairs = new HashMap<String, String>();
for (int i = 0; i < myArray.length(); i++) {
JSONObject j = myArray.optJSONObject(i);
Iterator it = j.keys();
while (it.hasNext()) {
String n = it.next();
pairs.put(n, j.getString(n));
}
}

Related

How to parse inner json objects

I need to parse this json,can any one help me to do this?
{
"his_data_bg":{
"history":[
{
"date":"2016-10-06 11:00:00",
"value":72,
"dataID":"639F1006A8A4C9965E5E8E558138450A"
}
]
}
}
i am using jackson
package parse;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonParsing {
public static void main(String[] args) {
String jsonString = "{\"his_data_bg\":{\"history\":[{\"date\":\"2016-10-06 11:00:00\",\"value\":72,\"dataID\":\"639F1006A8A4C9965E5E8E558138450A\"}]}}";
try {
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(jsonString);
System.out.println(node.get("his_data_bg").get("history"));
} catch (JsonProcessingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
output : [{"date":"2016-10-06 11:00:00","value":72,"dataID":"639F1006A8A4C9965E5E8E558138450A"}]
i think it may help you

json parsing using uri for listview in android

ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url = "http://jsonplaceholder.typicode.com/posts";
//JSON Node Names
// private static final String TAG_OS = "Employee";
private static final String TAG_USER= "userId";
private static final String TAG_NAME = "id";
private static final String TAG_TITLE = "title";
private static final String TAG_BODY = "body";
JSONArray android = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = new ArrayList<HashMap<String, String>>();
Btngetdata = (Button)findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
ver = (TextView)findViewById(R.id.user);
name = (TextView)findViewById(R.id.id);
api = (TextView)findViewById(R.id.titile);
body =(TextView)findViewById(R.id.body);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
android = json.getJSONArray("");
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String ver = c.getString(TAG_USER);
String name = c.getString(TAG_NAME);
String api = c.getString(TAG_TITLE);
String body =c.getString(TAG_BODY);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_USER, ver);
map.put(TAG_NAME, name);
map.put(TAG_TITLE, api);
map.put(TAG_BODY, body);
list.add(map);
List=(ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, list,
R.layout.list_v,
new String[] { TAG_USER,TAG_NAME, TAG_TITLE,TAG_BODY }, new int[] {
R.id.user,R.id.id, R.id.titile,R.id.body});
List.setAdapter(adapter);
List.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at "+list.get(+position).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
json parse:-
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, "iso-8859-1"), 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;
}
}
Logcat here
java.lang.NullPointerException: Attempt to invoke virtual method 'org.json.JSONArrayorg.json.JSONObject.getJSONArray(java.lang.String)' on a null object reference
at com.example.mind.sqlitedatabase.MainActivity$JSONParse.onPostExecute(MainActivity.java:134)
at com.example.mind.sqlitedatabase.MainActivity$JSONParse.onPostExecute(MainActivity.java:103)
at android.os.AsyncTask.finish(AsyncTask.java:636)
at android.os.AsyncTask.access$500(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Actually, I faced problem when I click get button to call uri for json parsing.
But when in android device json = null parsing...
Here I used Volley library, it handle the all the things which you did manually(Asynctask, httprequest for json).
I hope it may helps you
// JsonObject request
public void getJSONFromUrl(String url) {
RequestQueue queue = Volley.newRequestQueue(getActivity());
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Response", "Response" + response);
//handle the json response
handleResponse(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Error", "Error: " + error.getMessage());
}
});
queue.add(jsonObjReq);
}
// converting from json to Map using JsonHelper class
public void handleResponse(JSONObject response) {
Map<String, Object> map = new HashMap<>();
if(response != null){
try {
// JsonObject to Map
map = JsonHelper.toMap(response);
// boolean isSuccess = map.get("success")
// if(isSuccess){
//}
if (map.size() != 0){
// use the data
}
Log.d("MAp","map" + map);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
here below class will help converting json response to MAP, from map to json.
copied from https://gist.github.com/codebutler/2339666
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.*;
public class JsonHelper {
public static Object toJSON(Object object) throws JSONException {
if (object instanceof Map) {
JSONObject json = new JSONObject();
Map map = (Map) object;
for (Object key : map.keySet()) {
json.put(key.toString(), toJSON(map.get(key)));
}
return json;
} else if (object instanceof Iterable) {
JSONArray json = new JSONArray();
for (Object value : ((Iterable)object)) {
json.put(value);
}
return json;
} else {
return object;
}
}
public static boolean isEmptyObject(JSONObject object) {
return object.names() == null;
}
public static Map<String, Object> getMap(JSONObject object, String key) throws JSONException {
return toMap(object.getJSONObject(key));
}
public static Map<String, Object> toMap(JSONObject object) throws JSONException {
Map<String, Object> map = new HashMap();
Iterator keys = object.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
map.put(key, fromJson(object.get(key)));
}
return map;
}
public static List toList(JSONArray array) throws JSONException {
List list = new ArrayList();
for (int i = 0; i < array.length(); i++) {
list.add(fromJson(array.get(i)));
}
return list;
}
private static Object fromJson(Object json) throws JSONException {
if (json == JSONObject.NULL) {
return null;
} else if (json instanceof JSONObject) {
return toMap((JSONObject) json);
} else if (json instanceof JSONArray) {
return toList((JSONArray) json);
} else {
return json;
}
}
}
volley library usage
http://www.androidhive.info/2014/09/android-json-parsing-using-volley/

Remove Map Node from JSON

I am creating a JSON in Java:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.google.gson.Gson;
String json = null;
Map<String, String> data1 = new HashMap<String, String>();
Map<String, String> data2 = new HashMap<String, String>();
data1.put("name", "f1");
data1.put("key", "aa1");
data1.put("value", "21");
data2.put("name", "f2");
data2.put("key", "aa1");
data2.put("value", "22");
JSONObject json1 = new JSONObject(data1);
JSONObject json2 = new JSONObject(data2);
JSONArray array = new JSONArray();
array.put(json1);
array.put(json2);
JSONObject finalObject = new JSONObject();
try {
finalObject.put("DeltaRealTime", array);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
json = new Gson().toJson(finalObject);
What I get is the following:
{
"map": {
"DeltaRealTime": {
"myArrayList": [{
"map": {
"name": "f1",
"value": "21",
"key": "aa1"
}
}, {
"map": {
"name": "f2",
"value": "22",
"key": "aa1"
}
}]
}
}
}
But I do not want to have all these extra "map" nodes. What I can I do to remove them? Or what I can I do that I do not have them in the first place?
To simply convert JSONObject to String you can use the toString() meethod. I did the same thing as you did without using the Gson Library and I didn't get any map node.
import java.util.HashMap;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class checkTimeStamp {
public static void main(String[] args){
Map<String, String> data1 = new HashMap<String, String>();
Map<String, String> data2 = new HashMap<String, String>();
data1.put("Hello", "abc");
data1.put("Hello1", "abc");
data1.put("Hello2", "abc");
data2.put("Hello", "abc");
data2.put("Hello1", "abc");
data2.put("Hello2", "abc");
JSONObject json1 = new JSONObject(data1);
JSONObject json2 = new JSONObject(data2);
JSONArray array = new JSONArray();
array.put(json1);
array.put(json2);
JSONObject finalObj = new JSONObject();
try{
finalObj.put("RealTimeData", array);
}
catch(JSONException e){
e.printStackTrace();
}
String json = finalObj.toString();
System.out.println(json);
}
}
And the Output was:
{"RealTimeData":[{"Hello1":"abc","Hello2":"abc","Hello":"abc"},{"Hello1":"abc","Hello2":"abc","Hello":"abc"}]}
I would suggest using an Object to JSON string converter lib like Jackson. You can get a json str in three simple steps and dont have to create any JSON objects:
Steps
Create a POJO class
Populate the POJO object
Convert the object to a JSON string using the method as how below:
ObjectMapper mapper = new ObjectMapper();
mapper.writeValueAsString(FooPOJO);
Ref: http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/
My answer may help anyone in the future as none of the answers above worked for me. I just called toMap() on the JSONObject and all occurences of the map key were gone.
you can try as:
String requestBody=data1.toString();
String requestBody=data2.toString();

JSON parse to populate listview Android Studio

I am pulling my hair out over this. After numerous tutorials, I thought I found the perfect one (7th to be exact. But after following the tutorial, I found out that JSONparse is deprecated. Can someone please give me a solution for this. I just want to read an array from the url and populate a listview.
The array is:
{ "lotInfo":[{"lot":"A","spaces":"198","rates":"3.25"},
{"lot":"B","spaces":"165","rates":"7.50"}]}
MainActivity.Java:
package com.example.sahan.wtf;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends ListActivity {
private Context context;
private static String url = "http://192.168.0.199/get_info.php";
private static final String lot = "lot";
private static final String spaces = "spaces";
private static final String rates = "rates";
ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();
ListView lv ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new ProgressTask(MainActivity.this).execute();
}
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
public ProgressTask(ListActivity activity) {
Log.i("1", "Called");
context = activity;
dialog = new ProgressDialog(context);
}
private Context context;
protected void onPreExecute() {
this.dialog.setMessage("Progress start");
this.dialog.show();
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
ListAdapter adapter = new SimpleAdapter(context, jsonlist, R.layout.list_activity, new String[] { lot, spaces, rates }, new int[] { R.id.lot, R.id.spaces, R.id.rates });
setListAdapter(adapter);
lv = getListView();
}
protected Boolean doInBackground(final String... args) {
JSONParse jParser = new JSONParser();
JSONArray json = jParser.getJSONFromUrl(url);
for (int i = 0; i < json.length(); i++) {
try {
JSONObject c = json.getJSONObject(i);
String vlot = c.getString(lot);
String vspaces = c.getString(spaces);
String vrates = c.getString(rates);
HashMap<String, String> map = new HashMap<String, String>();
map.put(lot, vlot);
map.put(spaces, vspaces);
map.put(rates, vrates);
jsonlist.add(map);
} catch (JSONException e)
{
e.printStackTrace();
}
}
return null;
}
}
}
JSONParser.Java:
package com.example.sahan.wtf;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class JSONParser {
static InputStream is = null;
static JSONArray jarray = null;
static String json = "";
public JSONParser() {
}
public JSONArray getJSONFromUrl(String url) {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} else {
Log.e("Error....", "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
jarray = new JSONArray( builder.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return array;
}
}
The error I get is:
Error:(74, 13) error: cannot find symbol class JSONParse
It seems that you have a typo, instead of:
JSONParse jParser = new JSONParser();
Should be:
JSONParser jParser = new JSONParser();

Write a java program to get JSON data from URL

1) Write a java program to get JSON data from URL
http://echo.jsontest.com/Operand1/10/Operand2/5/Operator/+
2) Perform Mathematical operation in Java after reading JSON from above URL and print result.
example for above URL
Result = 10+5 = 15
3) The result should be dynamic and should change if we change values in above URLs
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Scanner;
import org.json.JSONException;
import org.json.JSONObject;
public class JsonReader {
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
public static void main(String[] args) throws IOException, JSONException {
Scanner in = new Scanner(System.in);
System.out.println("Enter the JSON URL :");
String url = in.next();
JSONObject json = readJsonFromUrl(url);
int op1= Integer.parseInt((String)json.get("Operand1"));
int op2= Integer.parseInt((String)json.get("Operand2"));
int result = op1+op2;
System.out.println("Result is : "+ result);
}
}