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();
Related
In my Spring project i created some tests that check the controllers/ http-api. Is there a way to get the json content of response as de-serialized object?
In other project i used rest assured and there methods to acquire results directly as expected objects.
Here is an example:
MvcResult result = rest.perform( get( "/api/byUser" ).param( "userName","test_user" ) )
.andExpect( status().is( HttpStatus.OK.value() ) ).andReturn();
String string = result.getResponse().getContentAsString();
The method returns a specific type as json. how to convert this json back to an object to tests its contents?
I know ways with jackson or with rest-assured but is there a way within spring/test/mockmvc
Like getContentAs(Class)
As far as I know MockHttpServletResponse (Unlike RestTemplate) doesn't have any method which could convert returned JSON to a particular type.
So what you could do is use Jackson ObjectMapper to convert JSON string to a particular type
Something like this
String json = rt.getResponse().getContentAsString();
SomeClass someClass = new ObjectMapper().readValue(json, SomeClass.class);
This will give you more control for you to assert different things.
Having said that, MockMvc::perform returns ResultActions which has a method andExpect which takes ResultMatcher. This has a lot of options to test the resulting json without converting it to an object.
For example
mvc.perform( .....
......
.andExpect(status().isOk())
.andExpect(jsonPath("$.firstname").value("john"))
.andExpect(jsonPath("$.lastname").value("doe"))
.andReturn();
This might be of use:
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.togondo.config.database.MappingConfig;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultHandler;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
#Slf4j
#Getter
public class CustomResponseHandler<T> implements ResultHandler {
private final Class<? extends Collection> collectionClass;
private T responseObject;
private String responseData;
private final Class<T> type;
private Map<String, String> headers;
private String contentType;
public CustomResponseHandler() {
this.type = null;
this.collectionClass = null;
}
public CustomResponseHandler(Class type) {
this.type = type;
this.collectionClass = null;
}
public CustomResponseHandler(Class type, Class<? extends Collection> collectionClass) {
this.type = type;
this.collectionClass = collectionClass;
}
protected <T> T responseToObject(MockHttpServletResponse response, Class<T> type) throws IOException {
String json = getResponseAsContentsAsString(response);
if (org.apache.commons.lang3.StringUtils.isEmpty(json)) {
return null;
}
return MappingConfig.getObjectMapper().readValue(json, type);
}
protected <T> T responseToObjectCollection(MockHttpServletResponse response, Class<? extends Collection> collectionType, Class<T> collectionContents) throws IOException {
String json = getResponseAsContentsAsString(response);
if (org.apache.commons.lang3.StringUtils.isEmpty(json)) {
return null;
}
ObjectMapper mapper = MappingConfig.getObjectMapper();
JavaType type = mapper.getTypeFactory().constructCollectionType(collectionType, collectionContents);
return mapper.readValue(json, type);
}
protected String getResponseAsContentsAsString(MockHttpServletResponse response) throws IOException {
String content = "";
BufferedReader br = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(response.getContentAsByteArray())));
String line;
while ((line = br.readLine()) != null)
content += line;
br.close();
return content;
}
#Override
public void handle(MvcResult result) throws Exception {
if( type != null ) {
if (collectionClass != null) {
responseObject = responseToObjectCollection(result.getResponse(), collectionClass, type);
} else {
responseObject = responseToObject(result.getResponse(), type);
}
}
else {
responseData = getResponseAsContentsAsString(result.getResponse());
}
headers = getHeaders(result);
contentType = result.getResponse().getContentType();
if (result.getResolvedException() != null) {
log.error("Exception: {}", result.getResponse().getErrorMessage());
log.error("Error: {}", result.getResolvedException());
}
}
private Map<String, String> getHeaders(MvcResult result) {
Map<String, String> headers = new HashMap<>();
result.getResponse().getHeaderNames().forEach(
header -> headers.put(header, result.getResponse().getHeader(header))
);
return headers;
}
public String getHeader(String headerName) {
return headers.get(headerName);
}
public String getContentType() {
return contentType;
}
}
And then use it in your tests like this:
CustomResponseHandler<MyObject> responseHandler = new CustomResponseHandler(MyObject.class);
mockMvc.perform(MockMvcRequestBuilders.get("/api/yourmom"))
.andDo(responseHandler)
.andExpect(status().isOk());
MyObject myObject = responseHandler.getResponseObject();
Or if you want to fetch collections:
CustomResponseHandler<Set<MyObject>> responseHandler = new CustomResponseHandler(MyObject.class, Set.class);
.
.
.
Set<MyObject> myObjectSet = responseHandler.getResponseObject();
Below is library app. In its current state, the app is only able to search for single words. Searches like "Harry Potter" yield no result. I was told to use an URLEncoder but I tried and even that didn't work. Below are my java files.'
MainActivity.java
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.app.LoaderManager;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.Loader;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements LoaderCallbacks<List<Books>>, SearchView.OnQueryTextListener {
LoaderManager loaderManager;
String mQuery;
SearchView mSearchView;
MenuItem mMenuSearchItem;
private static final String LOG_TAG = MainActivity.class.getName();
private static final String GOOGLE_REQUEST_URL = "https://www.googleapis.com/books/v1/volumes?maxResults=40&q=";
private String url = GOOGLE_REQUEST_URL + "android";
private static final int BOOK_LOADER_ID = 1;
private BookAdapter adapter;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView bookListView = (ListView) findViewById(R.id.list);
adapter = new BookAdapter(this, new ArrayList<Books>());
bookListView.setAdapter(adapter);
loaderManager = getLoaderManager();
loaderManager.initLoader(BOOK_LOADER_ID, null, this);
bookListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Books currentBook = adapter.getItem(position);
Uri bookUri = Uri.parse(currentBook.getUrl());
Intent websiteIntent = new Intent(Intent.ACTION_VIEW, bookUri);
startActivity(websiteIntent);
}
});
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
#Override
public boolean onQueryTextSubmit(String query) {
if(isOnline()){
url = GOOGLE_REQUEST_URL + query;
loaderManager.restartLoader(BOOK_LOADER_ID, null, this);
}else{
Toast.makeText(this, "No Internet Connection Found!", Toast.LENGTH_LONG).show();
}
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
mQuery = newText;
return false;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options_menu, menu);
mMenuSearchItem = menu.findItem(R.id.menu_search);
mSearchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();
if (mSearchView != null) {
mSearchView.setIconifiedByDefault(false);
mSearchView.setOnQueryTextListener(this);
mSearchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View view, boolean queryTextFocused) {
if (!queryTextFocused) {
if (TextUtils.isEmpty(mQuery))
adapter.clear();
}
}
});
}
return true;
}
#Override
public Loader<List<Books>> onCreateLoader(int i, Bundle bundle) {
return new BookLoader(this, url);
}
#Override
public void onLoadFinished(Loader<List<Books>> loader, List<Books> books) {
adapter.clear();
if (books != null && !books.isEmpty()) {
adapter.addAll(books);
}
}
#Override
public void onLoaderReset(Loader<List<Books>> loader) {
adapter.clear();
}
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
public Action getIndexApiAction() {
Thing object = new Thing.Builder()
.setName("Main Page") // TODO: Define a title for the content shown.
// TODO: Make sure this auto-generated URL is correct.
.setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
.build();
return new Action.Builder(Action.TYPE_VIEW)
.setObject(object)
.setActionStatus(Action.STATUS_TYPE_COMPLETED)
.build();
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
AppIndex.AppIndexApi.start(client, getIndexApiAction());
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
AppIndex.AppIndexApi.end(client, getIndexApiAction());
client.disconnect();
}
BookUtils.java
import android.text.TextUtils;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
public final class BookUtils {
private static final String LOG_TAG = BookUtils.class.getSimpleName();
private BookUtils() {}
public static List<Books> fetchBookData(String requestUrl) {
URL url = createUrl(requestUrl);
String jsonResponse = null;
try {jsonResponse = makeHttpRequest(url);}
catch (IOException e) {Log.e(LOG_TAG, "Problem making the HTTP request.", e);}
List<Books> books = extractFeatureFromJson(jsonResponse);
return books;
}
private static URL createUrl(String stringUrl) {
URL url = null;
try {url = new URL(stringUrl);}
catch (MalformedURLException e) {Log.e(LOG_TAG, "Problem building the URL ", e);}
return url;
}
private static String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";
if (url == null) {return jsonResponse;}
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(15000);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
if (urlConnection.getResponseCode() == 200) {
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
} else {Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());}
}
catch (IOException e) {Log.e(LOG_TAG, "Problem retrieving the book JSON results.", e);}
finally {
if (urlConnection != null) {urlConnection.disconnect();}
if (inputStream != null) {inputStream.close();}
}
return jsonResponse;
}
private static String readFromStream(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null) {
output.append(line);
line = reader.readLine();
}
}
return output.toString();
}
private static List<Books> extractFeatureFromJson(String bookJSON) {
if (TextUtils.isEmpty(bookJSON)) {return null;}
List<Books> books = new ArrayList<>();
try {
JSONObject jsonResponse = new JSONObject(bookJSON);
JSONArray booksArray = jsonResponse.getJSONArray("items");
for (int i = 0; i < booksArray.length(); i++) {
JSONObject currentBook = booksArray.getJSONObject(i);
JSONObject volumeInfo = currentBook.getJSONObject("volumeInfo");
JSONArray authorsArray = volumeInfo.getJSONArray("authors");
String title = "", publisher = "", publishedDate = "", language = "", pageCount = "", printType = "", maturityRating = "", authors = "";
if(volumeInfo.has("title")){
language = volumeInfo.getString("language");
}
for (int j = 0; j < authorsArray.length(); j++) {
if (volumeInfo.has("authors")){
authors = authorsArray.getString(j);
}
}
if(volumeInfo.has("publisher")){
publisher = volumeInfo.getString("publisher");
}
if(volumeInfo.has("publishedDate")){
publishedDate = volumeInfo.getString("publishedDate");
}
if(volumeInfo.has("language")){
language = volumeInfo.getString("language");
}
if(volumeInfo.has("pageCount")){
pageCount = volumeInfo.getString("pageCount");
}
if(volumeInfo.has("printType")){
printType = volumeInfo.getString("printType");
}
if(volumeInfo.has("maturityRating")){
maturityRating = volumeInfo.getString("maturityRating");
}
Books book = new Books(title, authors, publisher, publishedDate, language, pageCount, printType, maturityRating);
books.add(book);
}
}
catch (JSONException e) {Log.e("QueryUtils", "Problem parsing the book JSON results", e);}
return books;
}
}
Books.java
public class Books {
private String mTitle;
private String mAuthors;
private String mPublisher;
private String mPublishingDate;
private String mLanguage;
private String mCount;
private String mPrintType;
private String mMaturityRating;
private String mURL;
public Books(String title, String authors, String publisher, String publishingDate, String language, String count, String printType, String maturityRating) {
mTitle = title;
mAuthors = authors;
mPublisher = publisher;
mPublishingDate = publishingDate;
mLanguage = language;
mCount = count;
mPrintType = printType;
mMaturityRating = maturityRating;
}
public String getTitle() {return mTitle;}
public String getAuthors(){return mAuthors;}
public String getPublisher(){return mPublisher;}
public String getPublishedDate(){return mPublishingDate;}
public String getLanguage(){return mLanguage;}
public String getCount(){return mCount;}
public String getPrintType(){return mPrintType;}
public String getMaturityRating(){return mMaturityRating;}
public String getUrl() {return mURL;}
}
BookLoader.java
import android.content.AsyncTaskLoader;
import android.content.Context;
import java.util.List;
public class BookLoader extends AsyncTaskLoader<List<Books>> {
private static final String LOG_TAG = BookLoader.class.getName();
private String mUrl;
public BookLoader(Context context, String url) {
super(context);
mUrl = url;
}
#Override
protected void onStartLoading() {forceLoad();}
#Override
public List<Books> loadInBackground() {
if (mUrl == null) {return null;}
List<Books> books = BookUtils.fetchBookData(mUrl);
return books;
}
}
BookAdapter.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
public class BookAdapter extends ArrayAdapter<Books> {
public BookAdapter(Context context, List<Books> books) {
super(context, 0, books);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View listItemView = convertView;
if (listItemView == null) {listItemView = LayoutInflater.from(getContext()).inflate(R.layout.book_list_item, parent, false);}
Books currentBook = getItem(position);
TextView title = (TextView) listItemView.findViewById(R.id.book_title);
title.setText(currentBook.getTitle());
TextView authors = (TextView) listItemView.findViewById(R.id.book_author);
authors.setText(currentBook.getAuthors());
TextView publisher = (TextView) listItemView.findViewById(R.id.book_publisher);
publisher.setText(currentBook.getPublisher());
TextView publishingDate = (TextView) listItemView.findViewById(R.id.book_publishing_date);
publishingDate.setText(currentBook.getPublishedDate());
TextView language = (TextView) listItemView.findViewById(R.id.book_language);
language.setText(currentBook.getLanguage());
TextView pageCount = (TextView) listItemView.findViewById(R.id.book_page_count);
pageCount.setText(currentBook.getCount());
TextView printType = (TextView) listItemView.findViewById(R.id.book_print_type);
printType.setText(currentBook.getPrintType());
TextView maturityRating = (TextView) listItemView.findViewById(R.id.book_maturity_rating);
maturityRating.setText(currentBook.getMaturityRating());
return listItemView;
}
}
On my onQueryTextSubmit method, I tried replacing url = GOOGLE_REQUEST_URL + query; with:
Uri.Builder uriBuilder = Uri.parse(GOOGLE_REQUEST_URL).buildUpon().appendQueryParameter("q", query);
url = uriBuilder.toString();
But it didn't work.
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));
}
}
package com.test.mysql;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import com.test.mysql.FileReaderer;
public class automateImport {
/**
* #param args
* #throws ClassNotFoundException
*/
public static void main(String[] args) throws ClassNotFoundException, FileNotFoundException {
/* Class.forName("com.mysql.jdbc.Driver");
try {
Connection con = (Connection) DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mysql", "root", "root");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
FileReaderer fr = null;
String dirpath = "";
Scanner scanner1 = new Scanner(System.in);
while (true) {
System.out.println("Please give the directory:");
dirpath = scanner1.nextLine();
File fl = new File(dirpath);
System.out.println("f1"+fl.getPath());
if (fl.canRead()){
System.out.println("f2"+fl.getPath());
fr = new FileReaderer(fl);
break;
}
else{
System.out.println("Error:Directory does not exists");
}
}
}
}
package com.test.mysql;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
public class FileReaderer {
private final Pattern linePattern = Pattern.compile("^(\\w++)\\s++(\\w++)\\s*+$");
private final Pattern lineBreakPattern = Pattern.compile("\r?\n");
private final FileFilter txtFilter = new FileNameExtensionFilter("*.txt", "txt");
private final File txtFolder;
Connection con = null;
Statement stmt = null;
public FileReaderer(File txtFolder) {
this.txtFolder = txtFolder;
readFiles();
}
public List<Person> readFiles() {
try {
Class.forName("com.mysql.jdbc.Driver");
con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql", "root", "root");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
final List<Person> people = new LinkedList<>();
System.out.println("txt folder"+txtFolder.getPath());
for (final File txtFile : txtFolder.listFiles()) {
if (txtFilter.accept(txtFile)) {
System.out.println("txt Files " +txtFile.getName());
people.addAll(readFile(txtFile));
}
}
System.out.println("File Final List==>"+people);
insertData(con,stmt,people);
return people;
}
private List<Person> readFile(File txtFile) {
try (final Scanner scanner = new Scanner(txtFile)) {
/* scanner.useDelimiter(lineBreakPattern);
final Person person = new Person();
while (scanner.hasNext()) {
final String line = scanner.next();
final Matcher matcher = linePattern.matcher(line);
if (matcher.matches()) {
switch (matcher.group(1).toUpperCase()) {
case "ID":
person.setId(Integer.parseInt(matcher.group(2)));
break;
case "NAME":
person.setName(matcher.group(2));
break;
default:
throw new IOException("Illegal line '" + matcher.group() + "'.");
}
}
}*/
BufferedReader br = new BufferedReader(new FileReader(txtFile));
String currentLine = br.readLine();
List<Person> processPersonList = new ArrayList<Person>();
while (currentLine != null) {
String[] tokens = currentLine.split(",");
Person finalPerson = new Person();
finalPerson.setFirstName(tokens[0]);
finalPerson.setLastName(tokens[1]);
finalPerson.setSIN(tokens[2]);
currentLine = br.readLine();
processPersonList.add(finalPerson);
}
System.out.println("final list==>"+processPersonList);
br.close();
return processPersonList;
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
private void insertData(Connection con,Statement stmt,List<Person> pp){
System.out.print("\nInserting records into table...");
try{
for(Person pr:pp){
System.out.println("First Name " +pr.getFirstName()+" Second Name " +pr.getLastName()+"SIN Name " +pr.getSIN());
String sql = "INSERT INTO employee(first_name, last_name,sin) values (?,?,?)" ;
PreparedStatement preparedStmt = con.prepareStatement(sql);
preparedStmt.setString (1, pr.getFirstName());
preparedStmt.setString (2, pr.getLastName());
preparedStmt.setString (3, pr.getSIN());
preparedStmt.execute();
}
System.out.println(" SUCCESS!\n");
con.close();
} catch (Exception e)
{
System.err.println("Got an exception!");
System.err.println(e.getMessage());
}
}
}
package com.test.mysql;
public class Person {
private String firstName;
private String lastName;
private String SIN;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getSIN() {
return SIN;
}
public void setSIN(String sIN) {
SIN = sIN;
}
//
connection getting closed before insert into db & need to implement sorting
connection getting closed before insert into db & need to implement sorting
connection getting closed before insert into db & need to implement sorting
connection getting closed before insert into db & need to implement sorting
}
package com.test.readfile;
import java.util.Date;
public class Employee {
private long id;
private String firstName;
private String lastName;
private Double salary;
private String sin;
private Date dob;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Double getSalary() {
return salary;
}
public void setSalary(Double salary) {
this.salary = salary;
}
public String getSin() {
return sin;
}
public void setSin(String sin) {
this.sin = sin;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
}
package com.test.readfile;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
public class FileReaderer {
private final Pattern linePattern = Pattern.compile("^(\\w++)\\s++(\\w++)\\s*+$");
private final Pattern lineBreakPattern = Pattern.compile("\r?\n");
private final FileFilter txtFilter = new FileNameExtensionFilter("*.txt", "txt");
private final File txtFolder;
Connection con = null;
Statement stmt = null;
public FileReaderer(File txtFolder) {
this.txtFolder = txtFolder;
readFiles();
}
public List<Employee> readFiles() {
try {
Class.forName("com.mysql.jdbc.Driver");
con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql", "root", "ptlusrapp$246");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
final List<Employee> people = new LinkedList<>();
System.out.println("txt folder"+txtFolder.getPath());
for (final File txtFile : txtFolder.listFiles()) {
if (txtFilter.accept(txtFile)) {
System.out.println("txt Files " +txtFile.getName());
people.addAll(readFile(txtFile));
}
}
System.out.println("File Final List==>"+people);
insertData(con,stmt,people);
return people;
}
private List<Employee> readFile(File txtFile) {
try (final Scanner scanner = new Scanner(txtFile)) {
/* scanner.useDelimiter(lineBreakPattern);
final Employee Employee = new Employee();
while (scanner.hasNext()) {
final String line = scanner.next();
final Matcher matcher = linePattern.matcher(line);
if (matcher.matches()) {
switch (matcher.group(1).toUpperCase()) {
case "ID":
Employee.setId(Integer.parseInt(matcher.group(2)));
break;
case "NAME":
Employee.setName(matcher.group(2));
break;
default:
throw new IOException("Illegal line '" + matcher.group() + "'.");
}
}
}*/
BufferedReader br = new BufferedReader(new FileReader(txtFile));
String currentLine = br.readLine();
DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
java.util.Date convertedDate = null;
String splitterString="\\s";
List<Employee> processEmployeeList = new ArrayList<Employee>();
while (currentLine != null) {
if(currentLine.indexOf(",")>-1)
splitterString = ",";
else
splitterString = "\\|";
String[] tokens = currentLine.split(splitterString);
Employee finalEmployee = new Employee();
finalEmployee.setId(Long.parseLong(tokens[0]));
finalEmployee.setFirstName(tokens[1]);
finalEmployee.setLastName(tokens[2]);
finalEmployee.setSalary(Double.parseDouble(tokens[3]));
finalEmployee.setSin(tokens[4]);
try {
convertedDate = formatter.parse(tokens[5]);
finalEmployee.setDob(convertedDate);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// finalEmployee.setDob(convertedDate);
currentLine = br.readLine();
processEmployeeList.add(finalEmployee);
}
System.out.println("final list==>"+processEmployeeList);
br.close();
return processEmployeeList;
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
private void insertData(Connection con,Statement stmt,List<Employee> pp){
System.out.print("\nInserting records into table...");
try{
for(Employee pr:pp){
System.out.println("First Name " +pr.getFirstName()+" Second Name " +pr.getLastName()+"SIN Name " +pr.getSin() +"DOB: "+pr.getDob());
//String sql = "INSERT INTO employee(first_name, last_name,sin) values (?,?,?)" ;
String sql = "INSERT INTO employee(id,first_name,last_name,salary,sin,dob) values (?,?,?,?,?,?)" ;
PreparedStatement preparedStmt = con.prepareStatement(sql);
preparedStmt.setLong(1,pr.getId());
preparedStmt.setString (2, pr.getFirstName());
preparedStmt.setString (3, pr.getLastName());
preparedStmt.setDouble(4, pr.getSalary());
preparedStmt.setString (5, pr.getSin());
java.sql.Date sqlDate = new java.sql.Date(pr.getDob().getTime());
preparedStmt.setDate(6, sqlDate);
preparedStmt.execute();
}
System.out.println(" SUCCESS!\n");
con.close();
} catch (Exception e)
{
System.err.println("Got an exception!");
System.err.println(e.getMessage());
}
}
}
package com.test.readfile;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class AutomateImport {
/**
* #param args
* #throws ClassNotFoundException
*/
public static void main(String[] args) throws ClassNotFoundException, FileNotFoundException {
/* Class.forName("com.mysql.jdbc.Driver");
try {
Connection con = (Connection) DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mysql", "root", "root");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
FileReaderer fr = null;
String dirpath = "";
Scanner scanner1 = new Scanner(System.in);
while (true) {
System.out.println("Please give the directory:");
dirpath = scanner1.nextLine();
File fl = new File(dirpath);
System.out.println("f1"+fl.getPath());
if (fl.canRead()){
System.out.println("f2"+fl.getPath());
fr = new FileReaderer(fl);
break;
}
else{
System.out.println("Error:Directory does not exists");
}
}
}
}
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);
}
}