Convert JSONArray to Object? - simplejson

I have the following JSON and I want to create an Contact object from it. How we can do that using
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
</dependency>
Here is the String
{"totalSize":1,"done":true,"records":[{"attributes":{"type":"Contact","url":"/services/data/v40.0/sobjects/Contact/0037F000001rW9rQAE"},"Id":"0037F000001rW9rQAE","Name":"Chris Smith"}]}
I developed below code but how how to used JSONArray to get the details from it ?
JSONParser jsonParser = new JSONParser();
Object obj = jsonParser.parse(value);
JSONObject jsonObject = (JSONObject) obj;
JSONArray jsonArray = (JSONArray) jsonObject.get("records");
System.out.println("~~~~~~~~~~~>>> "+jsonArray);
List<Contact> contacts = new ArrayList<>();
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject rec = (JSONObject) jsonArray.get(i);
Contact c = new Contact();
c.setId(jsonArray.get(j).toString());
contacts.add(jsonArray.get(j).toString());
}

You can solve your issue like this but if you want to manage exceptions you should use the method getString(KEY), instead optString(KEY)
List<Contact> contacts = new ArrayList<>();
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject rec = (JSONObject) jsonArray.get(i);
Contact c = new Contact();
c.setId(rec.optString("Id"));
c.setName(rec.optString("Name"));
c.setAtributes(rec.optJSONObject("attributes"))
contacts.add(rec);
}

Related

Split the string array

I know this question was absolutely answered but i did not find solution.
I get response from web-service a Json string response that is ["11,22222","33,44444"].
I try this but did not work because string include these characters [ ] and first comma is in the here 11,22
StringBuilder result = new StringBuilder();
URL url2 = new URL(url);
HttpURLConnection conn = (HttpURLConnection) url2.openConnection();
conn.setRequestMethod("GET");
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
String res = new String(result);
String [] coordinates = res.split(",");
How can i separate this string like "11,22222" and "33,44444"
Just use JavaScriptSerializer.
public void Method(string json)
{
JavaScriptSerializer js = new JavaScriptSerializer();
List<string> results = js.Deserialize<List<string>>(json);
}
JsonArray jArray=new JsonArray(result);
StringBuffer s=new StringBuffer();
for(int i=0;i<jArray.length();i++)
{
s.append(jArray.getString(i));
Log.e(“singleValue”,jArray.getString(i));
}
Log.e(“responsed”,s.toString());
Since you are getting a json, you can easily convert it to JsonArray and iterate thorugh it.
Gson gson = new Gson();
JsonArray array = gson.fromJson(rd, JsonElement.class).getAsJsonArray();
for (JsonElement jsonElement : array) {
System.out.println(jsonElement.getAsString());
}
Hope this helps.

Getting data from JSONObject in JSONArray from JSONObject

{"location":{
"name":"New York","region":"New York","country":"United States of America","lat":40.71,"lon":-74.01,"tz_id":"America/New_York","localtime_epoch":1488124171,"localtime":"2017-02-26 10:49"},
"forecast":{
"forecastday":[{"date":"2017-02-26","date_epoch":1488067200,"day":{"maxtemp_c":5.2,"mintemp_c":1.0,"avgtemp_c":3.5,"maxwind_kph":28.1,
"astro":{"sunrise":"06:34 AM",...
I am programming a Weather App, but when I want to access the, for Example, date then Android Studio says that there is : No value for forecast. This is how I try to get the data:
JSONObject jsonObject = new JSONObject(data);
[...]
JSONObject forecastObject = Utils.getObject("forecast", jsonObject);
JSONArray forecastArray = forecastObject.getJSONArray("forecastday");
JSONObject forecastWeather = forecastArray.getJSONObject(0);
weather.currentCondition.setDate(Utils.getString("date", forecastWeather));
JSONObject dayObject = Utils.getObject("day", forecastWeather);
What am I doing wrong?? Can You help me?
Are you sure, that you want item at index 0 of this JSONArray? To get JSONArray from JSONObject, you call JSONArray array = object.getJSONArray("key"), then JSONObject newobject = array.getJSONObject(index).
public static Weather getWeather(String data){
Weather weather = new Weather();
//creat JSONObject from data
try {
JSONObject jsonObject = new JSONObject(data);
Place place = new Place();
JSONObject locationObject = Utils.getObject("location", jsonObject);
place.setLat(Utils.getFloat("lat", locationObject));
place.setLon(Utils.getFloat("lon", locationObject));
place.setCity(Utils.getString("name", locationObject));
place.setCountry(Utils.getString("country", locationObject));
place.setRegion(Utils.getString("region", locationObject));
place.setLocaltime(Utils.getString("localtime", locationObject));
weather.place=place;
JSONObject currentObject = Utils.getObject("current", jsonObject);
weather.currentCondition.setLastupdated(Utils.getString("last_updated", currentObject));
weather.currentCondition.setTemperature(Utils.getString("temp_c", currentObject));
weather.currentCondition.setWindkph(Utils.getString("wind_kph", currentObject));
weather.currentCondition.setHumidity(Utils.getFloat("humidity", currentObject));
weather.currentCondition.setCloud(Utils.getInt("cloud", currentObject));
weather.currentCondition.setFeelslike(Utils.getDouble("feelslike_c", currentObject));
weather.wind.setWinddir(Utils.getString("wind_dir", currentObject));
weather.currentCondition.setPreciption(Utils.getString("precip_mm", currentObject));
weather.currentCondition.setPressure(Utils.getFloat("pressure_mb", currentObject));
JSONObject iconObject = Utils.getObject("condition", currentObject);
weather.currentCondition.setIcon(Utils.getString("icon", iconObject));
weather.currentCondition.setDescription(Utils.getString("text", iconObject));
return weather;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
This is the function of how i get my data from the website apixu.com
This is how i connect:
public class WeatherHttpClient {
public String getWeatherData(String place){
HttpURLConnection connection = null;
InputStream inputStream = null;
try {
connection = (HttpURLConnection) (new URL(Utils.BASE_URL + place)).openConnection();
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.setDoInput(true);
connection.connect();
//Read response
StringBuffer stringBuffer = new StringBuffer();
inputStream = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = null;
while((line = bufferedReader.readLine())!=null){
stringBuffer.append(line+ "\r\n");
}
inputStream.close();
connection.disconnect();
return stringBuffer.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}

Creating JSONArray inside other JSONArray?

I have two classes Sale and ItemSale. I'm trying create a JSONArray with all objects of Sale and add all ItemSale in this JSONArray. The problem is I don't know how I can do it.
I need this: Sale:{id:1, data:2015-09-28, cliente_id:1}, ItemSale:[{produto:5, quantidade:10, valorUnitario:5.00, totalItem:50.00}], Sale:{id:2, data:2015-09-28, cliente_id:33}, ItemSale:[{produto:10, quantidade:1, valorUnitario:5.00, totalItem:5.00}, {produto:23, quantidade:1, valorUnitario:10.00, totalItem:10.00}, {produto:25, quantidade:1, valorUnitario:20.00, totalItem:20.00}]
I'm trying this.
private JSONObject getJSONObjectToSend(){
JSONObject jsonVendas = new JSONObject();
JSONArray jsonArrayVenda = new JSONArray();
JSONArray jsonArrayItems = new JSONArray();
VendaPersist vp = new VendaPersist(getActivity());
//list of sale
List<Sale> lista = vp.getAllVendasFinalizadas();
try {
if(lista.size() > 0){
for(Sale v : lista){
JSONObject jsonObjectVenda = new JSONObject();
//Sale
jsonObjectVenda.put("dataVenda", new SimpleDateFormat("yyyy-MM-dd").format(v.getDataVenda()));
jsonObjectVenda.put("cliente", v.getCliente().getId_ws());
jsonObjectVenda.put("usuario", v.getIdUsuario());
jsonArrayVenda.put(jsonObjectVenda);
//itens Sale
for(ItemSale iv : v.getListaItems()){
JSONObject jsonObjectIV = new JSONObject();
jsonObjectIV.put("produto", iv.getProduto().getId_ws());
jsonObjectIV.put("quantidade", iv.getQuantidade());
jsonObjectIV.put("valorUnitario", iv.getValorUnitario());
jsonObjectIV.put("valorTotal", iv.getTotalItem());
jsonArrayItems.put(jsonObjectIV);
}
jsonArrayVenda.put(jsonArrayItems);
jsonVendas.put("Sale", jsonArrayVenda);
}
}
} catch (JSONException e) {
Log.e(TAG, e.getLocalizedMessage());
}
return jsonVendas;
}
You are not constructing a JSONArray but a JSONObject.
JSONArray jsonArr = new JSONArray();
jsonArr.put(jsonVendas);

how to connect a Java app ( java code ) to cloudant?

I've java code in eclipse and I've done all the set up required between eclipse and IBM bluemix cloudant service
I am not sure how to update my code to enable cloudant in eclipse
can someone please help ?
you need to add a piece of code in CloudantClient.java file under source directory of your project.
Please add these lines in CloudantClient class:
String VCAP_SERVICES = System.getenv("VCAP_SERVICES");
JSONObject vcap;
vcap = (JSONObject) JSONObject.parse(VCAP_SERVICES);
cloudant = (JSONArray) vcap.get("cloudantNoSQULDB");
cloudantInstance = (JSONObject) cloudant.get(0);
cloudantCredentials = (JSONObject) cloudantInstance.get("credentials");
you can also put this piece of code in a try catch loop as well.
try {
String VCAP_SERVICES = System.getenv("VCAP_SERVICES");
JSONObject vcap;
vcap = (JSONObject) JSONObject.parse(VCAP_SERVICES);
cloudant = (JSONArray) vcap.get("cloudantNoSQULDB");
cloudantInstance = (JSONObject) cloudant.get(0);
cloudantCredentials = (JSONObject) cloudantInstance.get("credentials");
}
catch (IOException e) {
e.printStackTrace();
}
I hope it works!
You may use the Bluemix config parser library to automatically parse the VCAP_SERVICES env variable (https://github.com/icha024/bluemix-config-parser)
It simplifies the messy code into...
String username = BluemixConfigStore.getConfig().getCloudantNoSQLDB()
.getCredentials().getUsername();
String password = BluemixConfigStore.getConfig().getCloudantNoSQLDB()
.getCredentials().getPassword();
Then you can create a Cloudant client from it as usual:
CloudantClient cloudantClient = ClientBuilder.account(username)
.username(username)
.password(password)
.build();
You need to use VCAP_SERVICES env variable used in bluemix like below:
private JSONArray cloudant;
private JSONObject cloudantInstance;
private JSONObject cloudantCredentials;
public CloudantClient()
{
this.httpClient = null;
try {
String VCAP_SERVICES = System.getenv("VCAP_SERVICES");
JSONObject vcap;
vcap = (JSONObject) JSONObject.parse(VCAP_SERVICES);
cloudant = (JSONArray) vcap.get("cloudantNoSQLDB");
cloudantInstance = (JSONObject) cloudant.get(0);
cloudantCredentials = (JSONObject) cloudantInstance.get("credentials");
} catch (IOException e) {
e.printStackTrace();
}
this.port = Config.CLOUDANT_PORT;
this.host = (String) cloudantCredentials.get("host");
this.username = (String) cloudantCredentials.get("username");
this.password = (String) cloudantCredentials.get("password");
this.name = Config.CLOUDANT_NAME;
this.dbc = this.createDBConnector();
}

want to fetch the data from excel file

Data drven framework, where the values are changing for every case
public static void main(String[] args) throws BiffException, IOException {
Sheet s;
WebDriver driver = new FirefoxDriver();
FileInputStream fi = new FileInputStream("D:\\Nikhil\\FGX\\DataDriven.xlsx");
Workbook W = Workbook.getWorkbook(fi);
s = W.getSheet(0);
for(int row = 0;row <= s.getRows();row++)
{
String Username = s.getCell(0,row).getContents();
System.out.println("Username" +Username);
driver.get("http://********");
driver.findElement(By.xpath("//*[#id='LoginName']")).sendKeys(Username);
String password= s.getCell(1, row).getContents();
System.out.println("Password "+password);
driver.findElement(By.xpath("//*[#id='Password']")).sendKeys(password);
driver.findElement(By.xpath("html/body/form/div/div/div/div/fieldset/button")).click();
}
There are several reasons to get the BiffException look at Biff exception in Java.
Make sure you point the correct file, sheet, cell etc. You need to fetch and iterate the excel data. I may not answered directly to your answer, but the below code might help you,
List getData() { **Fetch the data
String path = "filepath";
List dataList = new ArrayList();
FileInputStream fis = null;
try {
fis = new FileInputStream(new File(path));
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheet("TestData");
java.util.Iterator rows = sheet.rowIterator();
while (rows.hasNext()) {
XSSFRow row = ((XSSFRow) rows.next());
// int r=row.getRowNum();
java.util.Iterator cells = row.cellIterator();
int i = 0;
String[] testData= new String[3];
while (cells.hasNext()) {
XSSFCell cell = (XSSFCell) cells.next();
String value = cell.getStringCellValue();
if (!value.equals(null)) {
testData [i] = value;
i++;
}
}
dataList.add(testData);
}
}
catch (Exception e) {
e.printStackTrace();
}
return dataList;
}
public Object[][] data() { **Store the data in desired format
#SuppressWarnings("rawtypes")
List dataList= getData();
Object a[][]=new Object[dataList.size()][2];
for(int i=1;i<dataList.size();i++){
String[] test=(String[]) dataList.get(i);
String username = test[0];
String password=test[1];
a[i][0]=username;
a[i][1]=password;
}
return a;

Resources