I'm fairly new to android development and I am trying to create an android application for currency conversion. I need to read JSON URL to get the rate. I get user input for AMOUNT, CURRENCYFROM and CURRENCYTO. The url I'm trying to read is the following: http://rate-exchange.appspot.com/currency?from=USD&to=EUR&q=1
Once url read I want to assign the values to variables. Specifically I'm trying to get the rate and multiply by user input for AMOUNT.
I want to get the Dictionaries(I think the JSON file has dictionaries) value and keys and convert it to data types variables such as int or string. Any help would be appreciated. Thanks
You can use this code :
public API_Rate_Model getRate() {
API_Rate_Model result = new API_Rate_Model();
try {
HttpResponse response;
HttpClient myClient = new DefaultHttpClient();
HttpPost myConnection = new HttpPost("http://rate-exchange.appspot.com/currency?from=USD&to=EUR&q=1");
try {
response = myClient.execute(myConnection);
String JSONString = EntityUtils.toString(response.getEntity(),
"UTF-8");
Log.i(BaseID.TAG, JSONString);
JSONObject json = null;
json = new JSONObject(JSONString);
result.setTo(json.getString("to"));
result.setRate(json.getDouble("rate"));
result.setFrom(json.getString("from"));
result.setValue(json.getDouble("v"));
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
API_Rate_Model Class :
public class API_Rate_Model {
private String to;
private Double rate;
private String from;
private Double value;
public API_001_Model() {
to = "";
rate = 0.0;
from = "";
value = 0.0;
}
public Double getRate() {
return rate;
}
public void setRate(Double rate) {
this.rate = rate;
}
public int getValue() {
return value;
}
public void setValue(Double value) {
this.value = value;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to= to;
}
}
this code will sent a post to the server then convert the response to string then process the JSON String response. I hope my answer can helps you, but if you have any question feel free to ask in the comment :)
Related
I need to convert a JSON response into Java Object, but I am gettin nullpointerException.
Here is my model class:
public class Cheque {
private String payeeName;
private String accountNumber;
private String ifsCode;
private String micr;
private String bankName;
public Cheque() {
super();
// TODO Auto-generated constructor stub
}
public Cheque(String payeeName, String accountNumber, String ifsCode, String micr, String bankName) {
super();
this.payeeName = payeeName;
this.accountNumber = accountNumber;
this.ifsCode = ifsCode;
this.micr = micr;
this.bankName = bankName;
}
public String getPayeeName() {
return payeeName;
}
public void setPayeeName(String payeeName) {
this.payeeName = payeeName;
}
public String getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
public String getIfsCode() {
return ifsCode;
}
public void setIfscCode(String ifsCode) {
this.ifsCode = ifsCode;
}
public String getMicr() {
return micr;
}
public void setMicr(String micr) {
this.micr = micr;
}
public String getBankName() {
return bankName;
}
public void setBankName(String bankName) {
this.bankName = bankName;
}
Below I am posting the method in which I am invoking a Python program and getting a Json response from it:
public class RunPython {
public static void main(String[] args) throws IOException,ScriptException,NullPointerException{
// TODO Auto-generated method stub
Process p = Runtime.getRuntime().exec("python <path to file>/reg.py");
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line ;
try {
while((line =in.readLine()) != null) {
System.out.println(line);
}
} finally {
in.close();
}
ObjectMapper mapper = new ObjectMapper();
try {
Cheque cheque = mapper.readValue(line, Cheque.class);
System.out.println("Java object :");
System.out.println(cheque);
}
catch (JsonGenerationException ex) {
ex.printStackTrace();
}
catch (JsonMappingException ex) {
ex.printStackTrace();
}
catch (IOException ex) {
ex.printStackTrace();
}}}
The JSON response which I am getting is:
{
"bankName": [
"Bank"
],
"accountNumber": [
"989898989898"
],
"ifsCode": [
"0000000"
],
"micr": [
"0000000"
],
"payeeName": [
"name"
]
}
After running the program I am getting the JSON response as expected, but while converting it to a Java object it is showing nullPointerException in the main thread. Help me out to find where I am making the mistake.
You consume/exhaust all your Process Inputstream here when printing it :
try {
while((line =in.readLine()) != null) {
System.out.println(line);
}
And later on when you call the below it's already null :
Cheque cheque = mapper.readValue(line, Cheque.class);
You'd have to process it in the above while loop, instead of only printing it out
When you reach the statement:
Cheque cheque = mapper.readValue(line, Cheque.class);
variable line is null.
So you can either rebuild the JSON string (with a StringBuilder), or remove the code that prints the response, and parse the JSON directly from p.getInputStream().
Your Java object has String value, but JSON has array type ([ ])
I want to parse a JSON object from an endpoint (this one here: https://api.coinmarketcap.com/v1/ticker/bitcoin/) and store the value in a variable at a specific attribute, which in this case is the name.
This the ERROR i get:
java.lang.IllegalStateException: Expected a name but was STRING...
AsyncTask.execute(new Runnable() {
#Override
public void run() {
// All your networking logic
// should be here
try {
String u = "https://api.coinmarketcap.com/v1/ticker/bitcoin";
URL coinMarketCapApi = new URL(u);
HttpsURLConnection myConnection = (HttpsURLConnection) coinMarketCapApi.openConnection();
myConnection.setRequestProperty("User-Agent", "my-rest-app-v0.1");
if (myConnection.getResponseCode() == 200) {
// Success
InputStream responseBody = myConnection.getInputStream();
InputStreamReader responseBodyReader =
new InputStreamReader(responseBody, "UTF-8");
JsonReader jsonReader = new JsonReader(responseBodyReader);
jsonReader.beginArray();
while (jsonReader.hasNext()) {
String key = jsonReader.nextName();
if (key.equals("name")) {
String value = jsonReader.nextName();
break; // Break out of the loop
} else {
jsonReader.skipValue();
}
}
jsonReader.close();
myConnection.disconnect();
} else {
// Error handling code goes here
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
you can convert the InputStream to String and then Create JSONArray from that string. like
StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, encoding);
String theString = writer.toString();
JSONArray jsonarray = new JSONArray(theString);
This way you don't have to manually construct the array.
Use this depandency for JSONArray
https://mvnrepository.com/artifact/org.json/json
You can fix the problem using gson.
https://github.com/google/gson
com.google.gson.stream.JsonReader jsonReader =
new com.google.gson.stream.JsonReader(new InputStreamReader(responseBody));
ArrayList<Coin> coins = new Gson().fromJson(jsonReader, Coin.class);
coins.forEach(coin -> System.out.println(coin.name));
public class Coin{
private String id;
private String name;
private String symbol;
private int rank;
#SerializedName("price_usd")
private double priceUsd;
...........
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getSymbol() {
return symbol;
}
public int getRank() {
return rank;
}
public double getPriceUsd() {
return priceUsd;
}
..........
}
I have chat app where i need to develop user online state and for this i am calling API in every 15 seconds on server, which will return all logged in users and their online state in 0(Offline) and 1(Online).
I need to show whether user is online or offline (leaves app not logged out) while chatting.I have 1 array list which shows when app is launch with all logged in user id and their details including their online state and i created second API which return users online state in JSON.I have following option to achieve users online state
Replace existing array list item:-I am getting User ID and their online state in JSON but i need to run loop in every 15 second which replace values in existing arraylist
Store JSON in someway where i can easily find user id and its state:- If i store JSON in array list i need to run loop to find ID and its state which i dont want to,So which is best way to store JSON so i can easily get user state by its User ID.
Here is how i am getting JSON
protected List<WrapperClass> doInBackground(Void... params) {
userSession=new UserSession(context,"Elaxer");
UserState_Update=new ArrayList<>();
String data = null;
try {
String ID=userSession.getUserID(); //Getting Value from shared pref
data = URLEncoder.encode("User_ID", "UTF-8") + "=" + URLEncoder.encode(ID, "UTF-8");
Log.d(TAG,"Login ID "+ ID);
Log.d(TAG,"DO IN BACKGROUND START ");
URL url=new URL(URL_Path_NearBy);
connection= (HttpURLConnection) url.openConnection();
Log.d(TAG,connection.toString());
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
//For POST Only - Begin
OutputStream os = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(data);
writer.flush();
writer.close();
os.close();
connection.connect();
InputStream inputStream=connection.getInputStream();
reader=new BufferedReader(new InputStreamReader(inputStream));
Log.d(TAG,"GET INPUT STREAM AND PUUTING INTO READER");
String line;
StringBuffer stringBuffer=new StringBuffer();
while ((line=reader.readLine())!=null){
stringBuffer.append(line);
}
String completeJSON=stringBuffer.toString();
Log.d(TAG,"JSON ARRAY START");
JSONObject parentArray=new JSONObject(completeJSON);
JSONArray jsonArray=parentArray.getJSONArray("uData");
String LastSeen;
int LoginStatus,User_ID;
int Rec_Online_Status;
for (int i = 0; i <jsonArray.length() ; i++) {
JSONObject childObject=jsonArray.getJSONObject(i);
LastSeen=childObject.getString("lastseen") ;
LoginStatus=childObject.getInt("login_status") ;
User_ID=childObject.getInt("User_ID");
String UseID= String.valueOf(User_ID);
Log.d(TAG,"JSON Values "+LastSeen+" "+LoginStatus+" "+User_ID);
WrapperClass wrapperClass=new WrapperClass(UseID,LoginStatus);
UserState_Update.add(wrapperClass);
}
return UserState_Update; //List<WrapperClass> UserState_Update
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
This is the response as JSON
{
"status": "SUCCESS",
"uData": [
{
"User_ID": "4",
"login_status": "1",
"lastseen": "0000-00-00 00:00:00"
},
{
"User_ID": "1",
"login_status": "0",
"lastseen": "0000-00-00 00:00:00"
},
{
"User_ID": "12",
"login_status": "1",
"lastseen": "0000-00-00 00:00:00"
},
{
"User_ID": "33",
"login_status": "0",
"lastseen": "0000-00-00 00:00:00"
}
]
}
Is this right way to get user online state? (I know FCM is right way but FCM currently not ready on app server side)
UPDATE 2:-As code recommended by #XngPro i implement on doinBackground
Map<String,Online_Status_Wrapper.User> map=new HashMap<>();
Online_Status_Wrapper wrapper=gson.fromJson(completeJSON,Online_Status_Wrapper.class);
Log.d(TAG,"Wrapper Get Data value "+wrapper.getuData());
Log.d(TAG,"Wrapper Get Status value "+wrapper.getStatus());
for (Online_Status_Wrapper.User u: wrapper.getuData()){
map.put(u.getUser_ID(),u);
}
Log.d(TAG,"State of Other User users "+map.get(12).getLogin_status());//HERE I AM GETTING NullPointerException
return map;
I think you should use a Java serialization/deserialization library like Gson.
Hope to help you~
Example
private static void bar() {
String jsonStr = "{\"status\":\"SUCCESS\",\"uData\":[{\"User_ID\":\"4\",\"login_status\":\"1\",\"lastseen\":\"0000-00-00 00:00:00\"},{\"User_ID\":\"1\",\"login_status\":\"0\",\"lastseen\":\"0000-00-00 00:00:00\"},{\"User_ID\":\"12\",\"login_status\":\"1\",\"lastseen\":\"0000-00-00 00:00:00\"},{\"User_ID\":\"33\",\"login_status\":\"0\",\"lastseen\":\"0000-00-00 00:00:00\"}]}";
Gson gson = new Gson();
UserFoo userFoo = gson.fromJson(jsonStr, UserFoo.class);
Map<String, UserFoo.User> map = new HashMap<>();
for (UserFoo.User u : userFoo.getUData()) {
map.put(u.getUser_ID(), u);
}
System.out.println("userId: 12, loginState: " + map.get("12").getLogin_status());
}
public static class UserFoo {
/**
* status : SUCCESS
* uData : [{"User_ID":"4","login_status":"1","lastseen":"0000-00-00 00:00:00"},{"User_ID":"1","login_status":"0","lastseen":"0000-00-00 00:00:00"},{"User_ID":"12","login_status":"1","lastseen":"0000-00-00 00:00:00"},{"User_ID":"33","login_status":"0","lastseen":"0000-00-00 00:00:00"}]
*/
private String status;
private List<User> uData;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public List<User> getUData() {
return uData;
}
public void setUData(List<User> uData) {
this.uData = uData;
}
public static class User {
/**
* User_ID : 4
* login_status : 1
* lastseen : 0000-00-00 00:00:00
*/
private String User_ID;
private String login_status;
private String lastseen;
public String getUser_ID() {
return User_ID;
}
public void setUser_ID(String User_ID) {
this.User_ID = User_ID;
}
public String getLogin_status() {
return login_status;
}
public void setLogin_status(String login_status) {
this.login_status = login_status;
}
public String getLastseen() {
return lastseen;
}
public void setLastseen(String lastseen) {
this.lastseen = lastseen;
}
}
}
public class Test {
public static void main(String[] args) {
bar();
}
private static void bar() {
String jsonStr = "{\"status\":\"SUCCESS\",\"uData\":[{\"User_ID\":\"4\",\"login_status\":\"1\",\"lastseen\":\"0000-00-00 00:00:00\"},{\"User_ID\":\"1\",\"login_status\":\"0\",\"lastseen\":\"0000-00-00 00:00:00\"},{\"User_ID\":\"12\",\"login_status\":\"1\",\"lastseen\":\"0000-00-00 00:00:00\"},{\"User_ID\":\"33\",\"login_status\":\"0\",\"lastseen\":\"0000-00-00 00:00:00\"}]}";
Gson gson = new Gson();
UserFoo userFoo = gson.fromJson(jsonStr, UserFoo.class);
Map<String, UserFoo.User> map = new HashMap<>();
for (UserFoo.User u : userFoo.getUData()) {
map.put(u.getUser_ID(), u);
}
System.out.println("userId: " + "12, loginState: " + map.get("12").getLogin_status());
}
public static class UserFoo {
/**
* status : SUCCESS
* uData : [{"User_ID":"4","login_status":"1","lastseen":"0000-00-00 00:00:00"},{"User_ID":"1","login_status":"0","lastseen":"0000-00-00 00:00:00"},{"User_ID":"12","login_status":"1","lastseen":"0000-00-00 00:00:00"},{"User_ID":"33","login_status":"0","lastseen":"0000-00-00 00:00:00"}]
*/
private String status;
private List<User> uData;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public List<User> getUData() {
return uData;
}
public void setUData(List<User> uData) {
this.uData = uData;
}
public static class User {
/**
* User_ID : 4
* login_status : 1
* lastseen : 0000-00-00 00:00:00
*/
private String User_ID;
private String login_status;
private String lastseen;
public String getUser_ID() {
return User_ID;
}
public void setUser_ID(String User_ID) {
this.User_ID = User_ID;
}
public String getLogin_status() {
return login_status;
}
public void setLogin_status(String login_status) {
this.login_status = login_status;
}
public String getLastseen() {
return lastseen;
}
public void setLastseen(String lastseen) {
this.lastseen = lastseen;
}
}
}
}
Print
I have been trying to extract the goolge places api photo reference but have not had any success. I was wondering if someone could help me. Below is my code:
// KEY Strings
public static String KEY_REFERENCE = "reference"; // id of the place
public static String KEY_NAME = "name"; // name of the place
public static String KEY_VICINITY = "vicinity"; // Place area name
public static String KEY_PHOTO = "photo_reference";
class LoadPlaces extends AsyncTask<String, String, String> {
/**
* getting google places JSON response
* */
protected String doInBackground(String... args) {
// creating Places class object
googlePlaces = new GooglePlaces();
try {
String types = MenuActivity.type;
String keyword = MenuActivity.keyword;
// get nearest places
nearPlaces = googlePlaces.search(gps.getLatitude(),gps.getLongitude(),
types, keyword);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed Places into LISTVIEW
* */
// Get JSON response status
String status = nearPlaces.status;
// Check for OK status
if (status.equals("OK")) {
// Successfully got places details
if (nearPlaces.results != null) {
// loop through each place
for (Place p : nearPlaces.results) {
HashMap<String, String> map = new HashMap<String, String>();
map.put(KEY_REFERENCE, p.reference);
map.put(KEY_NAME, p.name);
map.put(KEY_PHOTO,p.photo);
map.put(KEY_VICINITY, p.vicinity);
// adding HashMap to ArrayList
placesListItems.add(map);
}
// list adapter - removed rating
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, placesListItems,
R.layout.list_item, new String[] {
KEY_REFERENCE, KEY_NAME, KEY_VICINITY, KEY_PHOTO},
new int[] { R.id.reference, R.id.name, R.id.address, R.id.phptp});
// Adding data into ListView
lv.setAdapter(adapter);
}
}
}
Below is my code that performs the search and parses the data:
public class GooglePlaces {
/** Global instance of the HTTP transport. */
private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
private static final String LOG_KEY = "GGPlace";
// Google API Key
private static final String API_KEY = "";
// Google Places serach
private static final String PLACES_SEARCH_URL = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?&rankby=distance";
private double _latitude;
private double _longitude;
private double _radius;
private String address;
public PlacesList search(double latitude, double longitude, String types, String keyword)
throws Exception {
this._latitude = latitude;
this._longitude = longitude;
try {
HttpRequestFactory httpRequestFactory = createRequestFactory(HTTP_TRANSPORT);
HttpRequest request = httpRequestFactory.buildGetRequest(new GenericUrl(PLACES_SEARCH_URL));
request.getUrl().put("key", API_KEY);
request.getUrl().put("location", _latitude + "," + _longitude);
request.getUrl().put("sensor", "true");
if(types != null)
{
request.getUrl().put("types", types);
request.getUrl().put("keyword", keyword);
}
PlacesList list = request.execute().parseAs(PlacesList.class);
// Check log cat for places response status
Log.d("Places Status", "" + list.status);
return list;
} catch (HttpResponseException e) {
Log.e("Error:", e.getMessage());
return null;
}
}
public static HttpRequestFactory createRequestFactory(
final HttpTransport transport) {
return transport.createRequestFactory(new HttpRequestInitializer() {
public void initialize(HttpRequest request) {
GoogleHeaders headers = new GoogleHeaders();
headers.setApplicationName("APP NAME");
headers.gdataVersion="2";
request.setHeaders(headers);
JsonHttpParser parser = new JsonHttpParser(new JacksonFactory());
request.addParser(parser);
}
});
}
}
This is my PlaceList class:
public class PlacesList implements Serializable {
#Key
public String status;
#Key
public List<Place> results;
}
Here is my Place class:
public class Place implements Serializable {
#Key
public String id;
#Key
public String name;
#Key
public String reference;
#Key
public String vicinity;
#Key
public Geometry geometry;
#Key
public List<Photo> photos;
}
And finally my Photo class:
public class Photo implements Serializable {
#Key
public String photo_reference;
#Key
public int height;
#Key
public int width;
}
I guess I am calling or passing the photo_reference the wrong way. I am hoping there is someone out there that can help me out. I've been working on this for weeks and have almost completely given up.
Hi firstly your search url is wrong.
You have to follow this format:
https://developers.google.com/places/web-service/photos
Please see below for a complete example:
http://wptrafficanalyzer.in/blog/showing-nearby-places-with-photos-at-any-location-in-google-maps-android-api-v2/
If you download the source code, it will help you see how to fetch the json string in an array which is in another array.
The snippet below just answers the part where you have to fetch the image:
package in.wptrafficanalyzer.locationnearbyplacesphotos;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class PlaceJSONParser {
/** Receives a JSONObject and returns a list */
public Place[] parse(JSONObject jObject){
JSONArray jPlaces = null;
try {
/** Retrieves all the elements in the 'places' array */
jPlaces = jObject.getJSONArray("results");
} catch (JSONException e) {
e.printStackTrace();
}
/** Invoking getPlaces with the array of json object
* where each json object represent a place
*/
return getPlaces(jPlaces);
}
private Place[] getPlaces(JSONArray jPlaces){
int placesCount = jPlaces.length();
Place[] places = new Place[placesCount];
/** Taking each place, parses and adds to list object */
for(int i=0; i<placesCount;i++){
try {
/** Call getPlace with place JSON object to parse the place */
places[i] = getPlace((JSONObject)jPlaces.get(i));
} catch (JSONException e) {
e.printStackTrace();
}
}
return places;
}
/** Parsing the Place JSON object */
private Place getPlace(JSONObject jPlace){
Place place = new Place();
try {
// Extracting Place name, if available
if(!jPlace.isNull("name")){
place.mPlaceName = jPlace.getString("name");
}
// Extracting Place Vicinity, if available
if(!jPlace.isNull("vicinity")){
place.mVicinity = jPlace.getString("vicinity");
}
if(!jPlace.isNull("photos")){
JSONArray photos = jPlace.getJSONArray("photos");
place.mPhotos = new Photo[photos.length()];
for(int i=0;i<photos.length();i++){
place.mPhotos[i] = new Photo();
place.mPhotos[i].mWidth = ((JSONObject)photos.get(i)).getInt("width");
place.mPhotos[i].mHeight = ((JSONObject)photos.get(i)).getInt("height");
place.mPhotos[i].mPhotoReference = ((JSONObject)photos.get(i)).getString("photo_reference");
JSONArray attributions = ((JSONObject)photos.get(i)).getJSONArray("html_attributions");
place.mPhotos[i].mAttributions = new Attribution[attributions.length()];
for(int j=0;j<attributions.length();j++){
place.mPhotos[i].mAttributions[j] = new Attribution();
place.mPhotos[i].mAttributions[j].mHtmlAttribution = attributions.getString(j);
}
}
}
place.mLat = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lat");
place.mLng = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lng");
} catch (JSONException e) {
e.printStackTrace();
Log.d("EXCEPTION", e.toString());
}
return place;
}
}
I first misunderstood photo_reference as Base64 Encoded String. But it is not indeed it is a reference parameter to identify and fetch a photo from google maps API. Imagine this as a token parameter. So to fetch a photo with max-width 400 you can use below URL.
https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference=CnRtAAAATLZNl354RwP_9UKbQ_5Psy40texXePv4oAlgP4qNEkdIrkyse7rPXYGd9D_Uj1rVsQdWT4oRz4QrYAJNpFX7rzqqMlZw2h2E2y5IKMUZ7ouD_SlcHxYq1yL4KbKUv3qtWgTK0A6QbGh87GB3sscrHRIQiG2RrmU_jF4tENr9wGS_YxoUSSDrYjWmrNfeEHSGSc3FyhNLlBU&key=YOUR_API_KEY
For more details visit Google Places documentation
https://developers.google.com/places/web-service/photos
I study xstream these days.
But I found the xstream json tutorial which in its homepage is very simple.
I have an array as follows:
{
"mails":[
{
"uid":"ZC2027-mXOmcAtkfiztS0sEeJlkU25",
"relatedCardNums":"8299,0000,1531|8299,0000,1531",
"houseHolder":"",
"subject":"no-subject",
"receiveTime":"2012-05-27 00:00:00",
"bankName":"上海银行",
"cards":[]
}
],
"dealedNum":330,
"nextRequestDelay":"1",
"percent":"0",
"filterNum":410,
"resCode":"01",
"dealedBillNum":43,
"resMsg":"正在解析"
}
I want to convert this json string to a GetMailsDataResponseDto, but I dont know how to do?
Could you help me out?
package com.fund.etrading.ebankapp.base.credit.cardniu.ecardniu.dto;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.fund.etrading.ebankapp.base.credit.utils.FileUtils;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;
public class GetMailsDataResponseDto extends ResponseBaseDto{
protected int dealedNum;
protected String nextRequestDelay;
protected String percent;
protected int filterNum;
protected int dealedBillNum;
protected List mails = new ArrayList();
public List getMails() {
return mails;
}
public int getDealedNum() {
return dealedNum;
}
public String getNextRequestDelay() {
return nextRequestDelay;
}
public String getPercent() {
return percent;
}
public int getFilterNum() {
return filterNum;
}
public int getDealedBillNum() {
return dealedBillNum;
}
public void fromJson(String json){
try {
json = FileUtils.get_content("C:\\Documents and Settings\\Administrator\\workspace\\99fund_java\\src\\com\\fund\\etrading\\ebankapp\\base\\credit\\新建 文本文档 (2).txt");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
json = "{\"root\":" + json + "}";
XStream xstream = new XStream(new JettisonMappedXmlDriver());
xstream.alias("root", this.getClass());
//xstream.addImplicitCollection(this.getClass(), "mails");
xstream.alias("mail", MailDto.class);
//xstream.aliasField("cards", MailDto.class, "cards");
//xstream.aliasField("currencyData", CardDto.class, "currencyData");
//xstream.aliasField("data", CurrencyDataDto.class, "data");
xstream.fromXML(json, this);
}
}
package com.fund.etrading.ebankapp.base.credit.cardniu.ecardniu.dto;
import java.util.ArrayList;
import java.util.List;
import com.fund.etrading.ebankapp.base.credit.BaseDto;
public class MailDto extends BaseDto{
protected String uid;
protected String relatedCardNums;
protected String houseHolder;
protected String subject;
protected String receiveTime;
protected String bankName;
protected List cards = new ArrayList();
public String getUid() {
return uid;
}
public String getRelatedCardNums() {
return relatedCardNums;
}
public String getHouseHolder() {
return houseHolder;
}
public String getSubject() {
return subject;
}
public String getReceiveTime() {
return receiveTime;
}
public String getBankName() {
return bankName;
}
public List getCards() {
return cards;
}
}
thanks in advance!
If you want to convert json string to your custom class(ex.GetMailsDataResponseDto), I recommend Google Gson.
If you use Gson, yon don't need fromJosn() method in GetMailsDataResponseDto class.
If you only use json parsing and have experiences of java script, I recommend Djson parser(java library).
"Djson Parse version 0.8a" -- http://blog.indf.net/category/Apps/djson
j1.txt - tip: "none BOM & UTF-8"
....
public void fromJson(String json){
//(real-code)--start
//Var var = Djson.parse(json);
//(real-code)--end
//--test-code--start
Var var = null;
try {
var = Djson.parse(new File("d:\\j1.txt"));
} catch (IOException e) {
e.printStackTrace();
}
//--test-code--end
this.dealedNum = var.get("dealedNum").toInt();
this.nextRequestDelay = var.get("nextRequestDelay").toString();
this.percent = var.get("percent").toString();
this.filterNum = var.get("filterNum").toInt();
this.dealedBillNum = var.get("dealedBillNum").toInt();
for(int i=0; i<var.get("mails").size(); i++) {
this.mails.add(var.get("mails").get(i).toObject()); // MAP type setting...
}
}