How to parse inner json objects - json

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

Related

How to set the private member variable of a class in test method with powermock

I am writing a junit test for the below constructor. i tried to set the value of mapRecords variable using Membermodifier but still i get the zero as the size of list. being a newbie in junit i am not getting the exact idea to do it. if someone can help it would be appreciated.
public class Transform {
private MapMetadataDAO mapMetadataDAO;
private Map<String,String> srcTargetMap;
private List<MapMetadata> mapRecords;
public Transform(String transformationId) throws GenericFlowException {
try {
mapMetadataDAO=new MapMetadataDAO();
} catch (DAOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mapRecords = mapMetadataDAO.findMapMetadataByTransformationID(transformationId);
System.out.println(mapRecords.size());
if(mapRecords.isEmpty()){
throw new GenericFlowException("Map meta data is not defined for the transformationId "+transformationId);
}
map();
}
}
Test class :
If i don't create the object using new, i am not able to invoke the constructor
#RunWith(PowerMockRunner.class)
#PrepareForTest({Transform.class, MapMetadataDAO.class})
public class TransformTest {
#Test
public void constructorTest() throws Exception
{
PowerMockito.suppress(PowerMockito.constructor(MapMetadataDAO.class));
MapMetadataDAO dao = PowerMockito.mock(MapMetadataDAO.class);
MapMetadata mapMetaData = PowerMockito.mock(MapMetadata.class);
PowerMockito.whenNew(MapMetadataDAO.class).withNoArguments().thenReturn(dao);
List<MapMetadata> list = new ArrayList<>();
list.add(mapMetaData);
Transform trans = PowerMockito.mock(Transform.class, Mockito.CALLS_REAL_METHODS);
MemberModifier.field(Transform.class, "mapRecords").set(trans, list);
PowerMockito.when(dao.findMapMetadataByTransformationID("transformationID")).thenReturn(list);
Transform transform = new Transform("transformationId");
PowerMockito.whenNew(Transform.class).withAnyArguments().thenReturn(trans);
}
}
With some changes in your class I made it work
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
#RunWith(org.powermock.modules.junit4.PowerMockRunner.class)
#PrepareForTest({MapMetadataDAO.class, Transform.class})
public class TransformTest {
#Mock
private MapMetadataDAO mapMetadataDAO;
#Mock
private Map<String,String> srcTargetMap;
#InjectMocks
private Transform Transform = new Transform();
#Before
public void init() {
MockitoAnnotations.initMocks(this);
}
#Test
public void testConstructor() throws Exception {
List<MapMetadata> mapRecords = new ArrayList<MapMetadata>();
mapRecords.add(new MapMetadata());
PowerMockito.whenNew(MapMetadataDAO.class).withNoArguments().thenReturn(mapMetadataDAO);
PowerMockito.when(mapMetadataDAO.findMapMetadataByTransformationID(Mockito.anyString())).thenReturn(mapRecords);
Transform.getTransform("transformationId");
}
}
class Transform{
private MapMetadataDAO mapMetadataDAO;
private Map<String,String> srcTargetMap;
private List<MapMetadata> mapRecords;
public Transform() {}
public void getTransform(String transformationId){
try {
mapMetadataDAO=new MapMetadataDAO();
mapRecords = mapMetadataDAO.findMapMetadataByTransformationID(transformationId);
System.out.println(mapRecords.size());
if(mapRecords.isEmpty()){
throw new GenericFlowException("Map meta data is not defined for the transformationId "+transformationId);
}
map();
} catch (DAOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (GenericFlowException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void map() {}
}
let me know if this is what you needed
For ease of test rewrite your class like this:
public class Transform {
private MapMetadataDAO mapMetadataDAO;
private Map<String,String> srcTargetMap;
private List<MapMetadata> mapRecords;
public Transform(MapMetadataDAO mapMedatadaDAO, String transformationId) throws GenericFlowException {
mapRecords = mapMetadataDAO.findMapMetadataByTransformationID(transformationId);
System.out.println(mapRecords.size());
if(mapRecords.isEmpty()){
throw new GenericFlowException("Map meta data is not defined for the transformationId "+transformationId);
}
map();
}
}
And then your test:
#RunWith(PowerMockRunner.class)
#PrepareForTest({MapMetadataDAO.class})
public class TransformTest {
#Test
public void constructorTest() throws Exception
{
MapMetadata mapMetaData = new MapMetadata();
List<MapMetadata> list = new ArrayList<>();
list.add(mapMetaData);
MapMetadataDAO dao = PowerMockito.mock(MapMetadataDAO.class);
String transformationId = "transformationId";
PowerMockito.when(dao.findMapMetadataByTransformationID(transformationId)).thenReturn(list);
Transform transform = new Transform(dao, transformationId);
}
}

Unabel to submit form data using jersy to mysql database

This is the Database connection java file which will connect to mysql local databse
package com.example.dao;
import java.sql.Connection;
import java.sql.DriverManager;
public class Database {
public Connection getConnection() throws Exception
{
Connection connection = null;
try
{
String connectionURL = "jdbc:mysql://localhost:3306/test1";
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL,
"root", "root");
}
catch (Exception e)
{
e.printStackTrace();
}
return connection;
}
}
This is the web service file for getting and adding up the candidates using com.perpule/hello/plain to get simple hello message & /getCandidate to get all list of candidates
package com.example.webservice;
import java.util.ArrayList;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.UriInfo;
import org.apache.http.HttpServerConnection;
import com.example.dao.Candidate;
import com.example.model.CandidateManager;
import com.google.gson.Gson;
#Path("/hello")
public class SayHello {
ArrayList<Candidate> candidateArr= new ArrayList<Candidate>();
#Context
UriInfo uriInfo;
#Context
Request request;
#GET
#Path("/plain")
#Produces(MediaType.TEXT_PLAIN)
public String sayHelloPlain()
{
return "hello ";
}
#GET
#Path("/candidates")
#Produces(MediaType.TEXT_PLAIN)
public String CandidateList()
{
String candidates=null ;
try {
candidateArr= new CandidateManager().getCandidates();
Gson gson=new Gson();
candidates=gson.toJson(candidateArr);
}catch (Exception e) {
e.printStackTrace();
}
return candidates;
}
#POST
#Path("/addCandidates")
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
#Produces(MediaType.TEXT_PLAIN)
public void submitCandidates(#FormParam("name") String name,
#FormParam("pass") String pass,
#FormParam("phone") String phone, #FormParam("email") String
email,#FormParam("city") String city)
{
Candidate candidate =new Candidate();
candidate.setName(name);
candidate.setPass(pass);
candidate.setPhone(phone);
candidate.setCity(city);
candidate.setEmail(email);
CandidateManager candidateManager=new CandidateManager();
try {
candidateManager.addCandidates(candidate);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Model class
package com.example.model;
import java.sql.Connection;
import java.util.ArrayList;
import com.example.dao.Access;
import com.example.dao.Candidate;
import com.example.dao.Database;
public class CandidateManager {
public ArrayList<Candidate> getCandidates() throws Exception
{
ArrayList<Candidate> candidateList = new ArrayList<Candidate>();
Database db= new Database();
Connection con=db.getConnection();
Access access=new Access();
candidateList=access.getCandidates(con);
return candidateList;
}
public void addCandidates(Candidate candidate) throws Exception
{
// ArrayList<Candidate> candidateData = new ArrayList<Candidate>();
Database db= new Database();
Connection con=db.getConnection();
new Access().addCandidates(con,candidate);
}
}
This is the DAO class for execueteQuery purpose : code for addCandidate is here
package com.example.dao;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
public class Access {
ResultSet rs=null;
public ArrayList<Candidate> getCandidates(Connection connection) throws
SQLException{
ArrayList<Candidate> candidateList =new ArrayList<Candidate>();
String sql="select * from candidate";
PreparedStatement psmt =connection.prepareStatement(sql);
rs=psmt.executeQuery();
try {
while(rs.next())
{
Candidate candidateObj = new Candidate();
candidateObj.setName(rs.getString("name"));
candidateObj.setPass(rs.getString("pass"));
candidateObj.setEmail(rs.getString("email"));
candidateObj.setPhone(rs.getString("phone"));
candidateObj.setCity(rs.getString("city"));
candidateList.add(candidateObj);
}
}catch (SQLException e) {
e.printStackTrace();
}
return candidateList;
}
public void addCandidates(Connection connection, Candidate candidate)
throws SQLException
{
String sql="insert into candidate values(?,?,?,?,?)";
try {
PreparedStatement preparedStatement
=connection.prepareStatement(sql);
// preparedStatement.executeQuery();
preparedStatement.setString(1, candidate.name);
preparedStatement.setString(2, candidate.pass);
preparedStatement.setString(3, candidate.phone);
preparedStatement.setString(4, candidate.city);
preparedStatement.setString(5, candidate.phone);
preparedStatement.execute();
connection.close();
}catch (Exception e) {
System.err.println("Got an exception!");
System.err.println(e.getMessage());
}
}
}

Covert JSON hashmap to Java hashmap

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));
}
}

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();

How to get random access to a file on SD-Card by means of API presented for Lollipop?

My application uses Java class RandomAccessFile to read/write bytes to a file on SD card randomly by means of realization of SeekableByteChannel interface. Now I need rewrite it for Android 5.0 with new Lollipop API.
I have found the only way to read:
InputStream inputStream = getContentResolver().openInputStream(uri);
and write:
ParcelFileDescriptor pfd = getActivity().getContentResolver().openFileDescriptor(uri, "w");
FileOutputStream fileOutputStream = new FileOutputStream(pfd.getFileDescriptor());
from/to a file in new API.
I would like to have an ability to set channel in some random position and read/write bytes to that position. Is it possible to do that in new SDK 21? Does new SDK imply this way obtaining of channels:
FieInputChannel fieInputChannel = fileInputStream.getChannel();
FieOutputChannel fieOutputChannel = fileOutputStream.getChannel();
or some other approach?
It seems the only way to get a random read/write access to a file on SD card for SDK 21 (Lollipop) is as follows:
import android.content.Context;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import com.jetico.bestcrypt.FileManagerApplication;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class SecondaryCardChannel {//By analogy with the java.nio.channels.SeekableByteChannel
private FileChannel fileChannel;
private ParcelFileDescriptor pfd;
private boolean isInputChannel;
private long position;
public SecondaryCardChannel(Uri treeUri, Context context) {
try {
pfd = context.getContentResolver().openFileDescriptor(treeUri, "rw");
FileInputStream fis = new FileInputStream(pfd.getFileDescriptor());
fileChannel = fis.getChannel();
isInputChannel = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public int read(ByteBuffer buffer) {
if (!isInputChannel) {
try {
fileChannel.close();
FileInputStream fis = new FileInputStream(pfd.getFileDescriptor());
fileChannel = fis.getChannel();
isInputChannel = true;
} catch (IOException e) {
e.printStackTrace();
}
}
try {
fileChannel.position(position);
int bytesRead = fileChannel.read(buffer);
position = fileChannel.position();
return bytesRead;
} catch (IOException e) {
e.printStackTrace();
return -1;
}
}
public int write(ByteBuffer buffer) {
if (isInputChannel) {
try {
fileChannel.close();
FileOutputStream fos = new FileOutputStream(pfd.getFileDescriptor());
fileChannel = fos.getChannel();
isInputChannel = false;
} catch (IOException e) {
e.printStackTrace();
}
}
try {
fileChannel.position(position);
int bytesWrite = fileChannel.write(buffer);
position = fileChannel.position();
return bytesWrite;
} catch (IOException e) {
e.printStackTrace();
return -1;
}
}
public long position() throws IOException {
return position;
}
public SecondaryCardChannel position(long newPosition) throws IOException {
position = newPosition;
return this;
}
public long size() throws IOException {
return fileChannel.size();
}
public SecondaryCardChannel truncate(long size) throws IOException {
fileChannel.truncate(size);
return this;
}
}
EDIT 15/03/2017:
Little bit optimized version looks like
import android.content.Context;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class SecondaryCardChannel {
private ParcelFileDescriptor pfdInput, pfdOutput;
private FileInputStream fis;
private FileOutputStream fos;
private long position;
public SecondaryCardChannel(Uri treeUri, Context context) {
try {
pfdInput = context.getContentResolver().openFileDescriptor(treeUri, "r");
pfdOutput = context.getContentResolver().openFileDescriptor(treeUri, "rw");
fis = new FileInputStream(pfdInput.getFileDescriptor());
fos = new FileOutputStream(pfdOutput.getFileDescriptor());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public int read(ByteBuffer buffer) {
try {
FileChannel fch = fis.getChannel();
fch.position(position);
int bytesRead = fch.read(buffer);
position = fch.position();
return bytesRead;
} catch (IOException e) {
e.printStackTrace();
return -1;
}
}
public int write(ByteBuffer buffer) {
try {
FileChannel fch = fos.getChannel();
fch.position(position);
int bytesWrite = fch.write(buffer);
position = fch.position();
return bytesWrite;
} catch (IOException e) {
e.printStackTrace();
return -1;
}
}
public long position() throws IOException {
return position;
}
public SecondaryCardChannel position(long newPosition) throws IOException {
position = newPosition;
return this;
}
public long size() throws IOException {
return fis.getChannel().size();
}
public void force(boolean metadata) throws IOException {
fos.getChannel().force(metadata);
pfdOutput.getFileDescriptor().sync();
}
public long truncate(long size) throws Exception {
FileChannel fch = fos.getChannel();
try {
fch.truncate(size);
return fch.size();
} catch (Exception e){ // Attention! Truncate is broken on removable SD card of Android 5.0
e.printStackTrace();
return -1;
}
}
public void close() throws IOException {
FileChannel fch = fos.getChannel();
fch.close();
fos.close();
fis.close();
pfdInput.close();
pfdOutput.close();
}
}