Split the string array - arrays

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.

Related

Convert JSONArray to Object?

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

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

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;

unrecognised character when displaying delimited text on servlet

I'm working on a servlet that accepts zipfile and will unzip and display the content of the csv files.
So far i'm able to display a few records. However, as shown in the image below, one of the record is diplaying "question marks"/unrecognised characters.
I checked the csv file and it's perfectly fine. I also tried to delete the text and typed some other text, but still unsuccessful.
image of the problem:
https://dl.dropbox.com/u/11910420/Screen%20Shot%202012-09-07%20at%203.18.46%20PM.png
public class AdminBootStrap extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/plain");
PrintWriter out = resp.getWriter();
try {
ServletFileUpload upload = new ServletFileUpload();
FileItemIterator iterator = upload.getItemIterator(req);
while (iterator.hasNext()) {
FileItemStream item = iterator.next();
InputStream in = item.openStream();
if (item.isFormField()) {
out.println("Got a form field: "
+ item.getFieldName());
} else {
out.println("Got an uploaded file: "
+ item.getFieldName() + ", name = "
+ item.getName());
ZipInputStream zis = new ZipInputStream(
new BufferedInputStream(in));
ZipEntry entry;
// Read each entry from the ZipInputStream until no
// more entry found indicated by a null return value
// of the getNextEntry() method.
//
byte[] buf = new byte[5000];
int len;
String s = null;
while ((entry = zis.getNextEntry()) != null) {
out.println("Unzipping: " + entry.getName());
if (entry.getName().equalsIgnoreCase("booking.csv")) {
while ((len = zis.read(buf)) > 0) {
s = new String(buf);
String[] arrStr = s.split("\\n");
for (String a : arrStr) {
out.println(a);
}// end for
}
}
any ideas?
The culprit is s = new String(buf) because it decodes a string of bytes into a string of characters via a default encoding. Unfortunately the default encoding on GAE is US-ASCII.
You should the encoding of your CSV. For example for UTF-8 use:
s = new String(buf, "UTF-8");

Resources