I have a list of information returned from the server and I am putting it in arraylist called "items". I would like to know how I can extract just the departments and place them into a simple string array which I have named department list .
This is what the list looks like
[
{
"Department": "Mobile Development",
"Department": 22
},
{
" "Department": "IT Support",
"Department": 13
}]
This is what I have coded so far however I think there is a problem with the way I am trying to add in my for each .
private void loadCompanyInfo() {
//final Context context = this.getActivity();
final Context context = this.context;
Organization client = new Organization(context);
Organization.api(context).getCompanyInforamtion(client.getID()).enqueue(new Callback<Results<CostCentresResult>>() {
#Override
public void onResponse(Call<Results<CostCentresResult>> call, Response<Results<CostCentresResult>> response) {
if (response.isSuccessful()) {
try {
Items = new ArrayList<>();
companyInfoList = new ArrayList<>();
Items.addAll(response.body());
if(Items.contains("Department")) {
Items.get(Items.indexOf(0));
for (int i = 0; i < Items.size(); i++) {
companyInfoList.add(Items[0])
}
}
} catch (Exception ex ) {
ex.printStackTrace();
ex.getMessage();
ex.getCause();
ex.getClass();
}
}
}
#Override
public void onFailure(Call<Results<CostCentresResult>> call, Throwable t) {
// TODO: handle ex
Errors.handleException(t);
}
});
}
}
Following code will help you to get the list of department from your server response:
try {
ArrayList<String> mDepartmentList = new ArrayList<String>();
JSONArray serverResponseJsonArray = new JSONArray(response.body());
if (serverResponseJsonArray != null
&& serverResponseJsonArray.length() > 0) {
for (int i = 0; i < serverResponseJsonArray.length(); i++) {
JSONObject departmentJsonObj = serverResponseJsonArray
.getJSONObject(i);
if (departmentJsonObj != null
&& !departmentJsonObj.equals("")) {
if (departmentJsonObj.has("Department")) {
mDepartmentList.add(departmentJsonObj
.getString("Department"));
}
}
}
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
Related
Within my application, I am dynamically creating and returning customers in JSON format. I would like to differentiate each customer, so I am adding a comma after the creation of each customer, but I do not wish to add the comma separation to the last element, so I would like to remove it.
Hence, I need to access the last element and make the modification, but I am running into some problems when doing the same. I tried to do this but was unable to concatenate the same. I am unable to get the last customer without a comma. The following is the code I have:
public static Multi <String> generate(final Input input) {
final ObjectMapper objectMapper = new ObjectMapper();
try {
final Multi < String > generatedCustomer = Multi.createFrom().publisher(CustomerGenerator.createModels(input)).onItem().transform(
event - > {
try {
return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(event) + ",";
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
});
final Multi < String > lastCustomer = generatedEvents.select().last().onItem().transform(i - > i.substring(0, i.length() - 1));
return Multi.createBy().concatenating().streams(generatedCustomer, lastCustomer);
} catch (Exception e) {
throw new CustomerException("Exception occurred during the generation of Customer : " + e);
}
}
How to achieve this?
Updated
My application currently produces customer information in the following format asynchronously, so I would like to add a wrapper to it and make it look like the following JSON.
{
"name": "Batman",
"age": 45,
"city": "gotham"
}
I would like to add a wrapper to it and make it like this:
{
"isA": "customerDocument",
"createdOn": "2022-10-10T12:29:43",
"customerBody": {
"customerList": [
{
"name": "Batman",
"age": 45,
"city": "gotham"
},
{
"name": "superman",
"age": 50,
"city": "moon"
}
]
}
}
Hence, I have added a code something like this:
public static Multi < String > generate(final Input input) {
final ObjectMapper objectMapper = new ObjectMapper();
try {
final Multi < String > beginDocument = Multi.createFrom().items("\"isA\":\"customerDocument\", \"creationDate\":\"" + Instant.now().toString() + "\", \"customerBody\":{ \"customerList\":[");
final Multi < String > generatedCustomer = Multi.createFrom().publisher(CustomerGenerator.createModels(input)).onItem().transform(
event - > {
try {
return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(event) + ",";
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
});
final Multi < String > lastCustomer = generatedEvents.select().last().onItem().transform(i - > i.substring(0, i.length() - 1));
return Multi.createBy().concatenating().streams(beginDocument, generatedCustomer, lastCustomer, Multi.createFrom().items("]}}"));
} catch (Exception e) {
throw new CustomerException("Exception occurred during the generation of Customer : " + e);
}
}
This should do what you've asked:
public static Multi <String> generate(final Input input) {
final ObjectMapper objectMapper = new ObjectMapper();
try {
final Multi<String> generatedCustomer = Multi.createFrom().publisher(CustomerGenerator.createModels(input)).onItem().transform(
event - > {
try {
return objectMapper
.writerWithDefaultPrettyPrinter()
.writeValueAsString(event);
} catch (JsonProcessingException e) {
e.printStackTrace();
return null;
}
});
Multi<String> customersMulti = generatedCustomer
.skip().last().map( s -> s + "," );
Multi<String> lastMulti = generatedCustomer
.select().last();
return customersMulti.onCompletion().switchTo(lastMulti);
} catch (Exception e) {
throw new CustomerException("Exception occurred during the generation of Customer : " + e);
}
}
You can find more information in the documentation
The following is something I tried and it worked:
public static Multi < String > generate(final Input input) {
final ObjectMapper objectMapper = new ObjectMapper();
try {
final Multi < String > beginDocument = Multi.createFrom().items("\"isA\":\"customerDocument\", \"creationDate\":\"" + Instant.now().toString() + "\", \"customerBody\":{ \"customerList\":[");
final AtomicBoolean firstEntry = new AtomicBoolean(true);
final Multi < String > generatedCustomer = Multi.createFrom().publisher(CustomerGenerator.createModels(input)).onItem().transform(
event - > {
try {
if (firstEntry.getAndSet(false)) {
return objectMapper
.writerWithDefaultPrettyPrinter()
.writeValueAsString(event);
}
return "," +
objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(event);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
});
return Multi.createBy().concatenating().streams(beginDocument, generatedCustomer, Multi.createFrom().items("]}}"));
} catch (Exception e) {
throw new CustomerException("Exception occurred during the generation of Customer : " + e);
}
}
How can i get the values of a json key in Java here is my code
private void getWebApiData() {
String WebDataUrl = "myjsonfileurl";
new AsyncHttpTask.execute(WebDataUrl);
}
#SuppressLint("StaticFieldLeak")
public class AsyncHttpTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpsURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpsURLConnection) url.openConnection();
if (result != null) {
String response = streamToString(urlConnection.getInputStream());
parseResult(response);
return result;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
if (result != null) {
newsAdapter = new NewsAdapter(getActivity(), newsClassList);
listView.setAdapter(newsAdapter);
Toast.makeText(getContext(), "Data Loaded Successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(), "Failed to load data!", Toast.LENGTH_SHORT).show();
}
progressBar.setVisibility(View.GONE);
}
}
private String streamToString(InputStream stream) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
String line;
String result = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
// Close stream
if (null != stream) {
stream.close();
}
return result;
}
private void parseResult_GetWebData(String result) {
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray("books");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject articleObject = jsonArray.getJSONObject(i);
JSONObject sourceObject = articleObject.getJSONObject("A");
String name = sourceObject.optString("name");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
My json file
{
"books": [
{
"A": [
{
"Amazonite": {
"name": "Amazonite",
"image": "www.google.com"
},
"Amethyst": {
"name": "Amethyst",
"image": "www.google.com"
}
}
],
"B": [
{
"Beryl": {
"name": "Beryl",
"image": "www.google.com"
},
"BloodStone": {
"name": "Bloodstone",
"image": "www.google.com"
}
}
]
}
]
}
What i would like is how to get the values of data under the Alphabet A that is Amazonite and Amethyst and the value of data under Alphabet B but the could i have just give me empty text field nothing no data is being populated.
I have tried with this code but the values retures "null"
private void parseResult_GetWebData(String result) {
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray("books");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject articleObject = jsonArray.getJSONObject(i);
String name = String.valueOf(articleObject.optJSONObject("A"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
I am not sure what you really want, but if you just want to get "Amazonite and Amethyst" as you responded under OP, you can try this:
Code snippet
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject articleObject = jsonArray.getJSONObject(i);
JSONArray jsonArrayA = articleObject.getJSONArray("A");
for (int j = 0; j < jsonArrayA.length(); j++) {
JSONObject obj = jsonArrayA.getJSONObject(j);
System.out.println(obj.names());
obj.names().forEach(e -> {
System.out.println(obj.getJSONObject(e.toString()).get("name"));
});
}
}
Console output
["Amazonite","Amethyst"]
Amazonite
Amethyst
Update
I am not sure which name you want to retrieve because both Amazonite and Amethyst appear two times in JSON array A, so I provide two ways to show them as follows:
List<String> names = new ArrayList<>();
List<String> innerNames = new ArrayList<>();
for (int j = 0; j < jsonArrayA.length(); j++) {
JSONObject obj = jsonArrayA.getJSONObject(j);
JSONArray keys = obj.names();
for (int k = 0; k < keys.length(); k++) {
String name = keys.getString(k);
String innerName = obj.getJSONObject(keys.optString(k)).getString("name");
System.out.printf("name: %s, inner name: %s\n", name, innerName);
names.add(name);
innerNames.add(innerName);
}
}
System.out.println(names.toString());
System.out.println(innerNames.toString());
Console output
name: Amazonite, inner name: Amazonite
name: Amethyst, inner name: Amethyst
[Amazonite, Amethyst]
[Amazonite, Amethyst]
I start using google app engine but I'm a beginner.
I created a web application and I added the library Jsoup.
I'm trying to parse a lot of data from a web site but when I deploy the application I get this error:
Error: Server Error
The server encountered an error and could not complete your request.
Please try again in 30 seconds.
here is my code :
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/plain");
resp.getWriter().println("{\"Restaurant\":[");
listPages = new ArrayList<>();
listRestaurant = new ArrayList<>();
listUrlRestaurant = new ArrayList<>();
listObj = new ArrayList<>();
try {
doc = Jsoup.connect(url).userAgent("Mozilla").timeout(60000).get();
//System.out.println(doc.select("strong.next.page-numbers").text());
int i=1;
while(doc.select("strong.next.page-numbers").text().contains("SUIV")){
listPages.add(url);
//System.out.println("exist : "+url);
//System.out.println("*******");
//restaurants = doc.select("div.listing_img > a");
url = url.replace("page/"+i+"/", "page/"+(i+1)+"/");
i=i+1;
//System.out.println("*****"+url);
doc = Jsoup.connect(url).userAgent("Mozilla").timeout(60000).get();
//ParsingRestaurant(restaurants,resp,doc);
}
} catch (IOException e) {
e.printStackTrace();
}
//System.out.println(listPages.size());
try{
for (int i = 0; i < listPages.size(); i++) {
doc2 = Jsoup.connect(listPages.get(i)).userAgent("Mozilla").timeout(60000).get();
restaurants = doc2.select("div.listing_img > a");
for (Element element : restaurants) {
listUrlRestaurant.add(element.attr("href"));
//System.out.println(element.attr("href"));
}
}
} catch (IOException e) {
e.printStackTrace();
}
//System.out.println(listUrlRestaurant.size());
for (int i = 0; i < listUrlRestaurant.size(); i++) {
ParsingRestaurant(listUrlRestaurant.get(i), resp, doc3,listObj);
}
for (int i = 0; i < listObj.size(); i++) {
if (i!=listObj.size()) {
resp.getWriter().println(listObj.get(i)+",");
}else{
resp.getWriter().println(listObj.get(i));
}
}
resp.getWriter().println("]}");
}
private void ParsingRestaurant(String url, HttpServletResponse resp, Document doc,List<String> listObj) {
// TODO Auto-generated method stub
Gson gson = new GsonBuilder().setPrettyPrinting().create();
Restaurant obj = new Restaurant();
try {
doc = Jsoup.connect(url).userAgent("Mozilla").timeout(60000).get();
name = doc.select("h1.entry-title").first();
obj.setName(name.text());
adress = doc.select("span#frontend_address").first();
obj.setAdress(adress.text());
facebook = doc.select("a#facebook").first();
if (facebook == null) {
obj.setFacebook("empty");
}else{
obj.setFacebook(facebook.attr("href"));
}
phone = doc.select("span.entry-phone.frontend_phone.listing_custom").first();
if (phone == null) {
obj.setPhone("empty");
}else{
obj.setPhone(phone.text());
}
time = doc.select("span.entry-listing_timing.frontend_listing_timing.listing_custom").first();
if (time == null) {
obj.setPhone("empty");
}else{
obj.setTime(time.text());
}
map = doc.select("div.google-map-directory > a ").first();
//System.out.println(name.text()+adress.text()+facebook.attr("href")+phone.text()+time.text());
String location = map.attr("href");
location = location.replace("http://www.google.com/maps/dir/Current+Location/", "");
String[] output = location.split(",");
obj.setLongitude(output[0]);
obj.setLatitude(output[1]);
images = doc.select("a.listing_img.galerie_listing");
for (Element e : images) {
obj.images.add(e.attr("href"));
}
details = doc.select("div#listing_apercu > div");
for (Element e : details) {
//System.out.println(e.select("label").text());
obj.titles.add(e.select("label").text());
String x = e.select("p > span").text();
for (int j = 1; j < x.length(); j++) {
if (Character.isUpperCase(x.charAt(j))) {
x = changeCharInPosition(j-1, ',', x);
}
}
obj.details.add(x);
}
String json = gson.toJson(obj);
listObj.add(json);
} catch (IOException e) {
e.printStackTrace();
}
}
public String changeCharInPosition(int position, char ch, String str){
char[] charArray = str.toCharArray();
charArray[position] = ch;
return new String(charArray);
}
}
any idea about the problem?!
Im trying to download data from a server in the form of a JSON object, parse that object then use the data elsewhere in my app.
Ive created a class which downloads the data (confirmed with a Log.v statement)
The trouble is that i want to display the results in a RecyclerView and the List of objects that i generate after parsing the JSON response does not get generated until after the adapter method is called from my main class.
So my question is, given the code below, how can i ensure that the on response method only exits once the parseResponse method has finished. Currently i am returning the (Null) _releaseList from my requestAndPareseReleaseList method.
public class ParseReleaseJSON extends JSONObject {
String _url;
List<ReleaseInfo> _releaseList = Collections.emptyList();
ParseReleaseJSON(String url) {
super();
_url = url;
}
public List<ReleaseInfo> requestAndParseReleaseList(Context _context){
JsonObjectRequest jsObReq = new JsonObjectRequest(Request.Method.GET, _url, (String) null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
releaseList = parseResponse(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.v("err", "nosuccess");
}
});
MySingleton.getInstance(_context).addToRequestQueue(jsObReq);
return _releaseList;
}
private List parseResponse(JSONObject response) {
List<ReleaseInfo> list = new ArrayList<>();
if(response == null || response.length() == 0){
return list;
}
try {
if(response.has("results")){
JSONArray resultsArray = response.getJSONArray("results");
for(int i = 0, j = 6; i < j; i++){
ReleaseInfo release = new ReleaseInfo();
JSONObject tempObj = resultsArray.getJSONObject(i);
release.title = tempObj.getString("title");
release.date = tempObj.getString("date");
list.add(release);
}
return list;
}
} catch (JSONException e) {
e.printStackTrace();
}
return list;
}
}
I would still need some help with my dynamic selectlist.
I have the sript:
function getMains(element) {
var subjectgroup = element.value;
var select_element;
select_element = '#mains';
$(select_element).html('');
$(select_element).append($("<option></option>").attr("value","none").html(""));
// $(select_element).append($("<option></option>").attr("value","all").html(""));
if (element.value==''||element.value=='none'||element.value=='all')
return;
$.ajax({
type: 'GET',
url: 'getmainsubjects.html',
dataType: 'json',
data: ({id:data}),
success: function(data) {
$.each(function(data) {
if (!subjectgroup) {
$(select_element).append($(" <option>").attr("value",data.id,"items",data).html(data.description));
} else {
$(select_element).append($("<option>").attr("value",data.id,"items",data).html(data.description));
}
});
},
error: function(data) {
//alert("This failed!");
}
});
}
$('select#subjectgroups').ready(function(){
$("select#subjectgroups").find("option").each(function(i) {
if ($(this).val()!='all'&&$(this).val()!='none') {
$(this).append( " " + $(this).val() );
}
});
});
$('select#mains').ready(function(){
$("select#mains").find("option").each(function(i) {
if ($(this).val()!='all'&&$(this).val()!='none') {
$(this).append( " " + $(this).val() );
}
});
});
And the method:
#RequestMapping(method = RequestMethod.GET, params="id", value = "/getmainsubjects")
#ResponseBody
public String getMainSubjects( #RequestParam("id") int id) {
List<MainSubjectsSimple> mains = database.getMainSubjectsSimple(id, Localization.getLanguage());
//System.out.println(mains.size());
HashMap hm = new HashMap();
for (MainSubjectsSimple mss: mains) {
try {
hm.put("id",mss.getId());
hm.put("description", mss.getDescription());
} catch (NoSuchMessageException e) {
//hm.add(Integer.valueOf(mss.getId().toString(), translate(mss.getTranslationCode(),new Locale("fi")));
}
}
String json = null;
String _json = null;
try {
_json = HtmlEntityEncoder.encode(JsonUtils.javaToStr(hm));
} catch (Exception e) {
}
return _json;
}
I think I'm not looping the right values. Mains selectlist should be populated based on other selectlist so that the object's id is the value and description the label. Right now calling the url written in script returns only first object as json, not all of them, and the objects are not shown in mains selectlist.
You are putting the same keys over and over again to the Map hm:
HashMap hm = new HashMap();
for (MainSubjectsSimple mss: mains) {
try {
hm.put("id",mss.getId());
hm.put("description", mss.getDescription());
} catch (NoSuchMessageException e) {
//hm.add(Integer.valueOf(mss.getId().toString(),
translate(mss.getTranslationCode(),new Locale("fi")));
}
}
You need to use different keys for each entry in mains or use a collection (e.g. ArrayList) of Maps. An example of the latter:
List hms = new ArrayList();
for (MainSubjectsSimple mss: mains) {
try {
HashMap hm = new HashMap();
hm.put("id",mss.getId());
hm.put("description", mss.getDescription());
hms.add(hm);
} catch (NoSuchMessageException e) {
//hm.add(Integer.valueOf(mss.getId().toString(), translate(mss.getTranslationCode(),new Locale("fi")));
}
}
...
try {
_json = HtmlEntityEncoder.encode(JsonUtils.javaToStr(hms));
} catch (Exception e) {
}
I'm not familiar with the utils (JsonUtils) you are using so this might not work directly but the principle is the same anyways.