I have a c# web project that has some REST request to do to get data from the db. My problem is: I have a GET call which return an array of the size of the number of rows returned by the query but every object is empty. While I'm debugging, every object has all the data I need but when the data reach the javascript the array is full of empty object. Where am I wrong?
This is the request on the .js file:
$.get("api/giacenzemobile/getGiacenze", function (data) {
console.log(data)
});
This is the function on the model file (.cs)
public static List<GiacenzeMobile> EstraiGiacenzeMobile()
{
List<GiacenzeMobile> giacenzeMobile = new List<GiacenzeMobile>();
SqlCommand cmd = null;
SqlConnection sqlconn = null;
using (sqlconn = new SqlConnection(Configurazione.ConnessioneDB))
{
sqlconn.Open();
string query = "...";
cmd = new SqlCommand(query, sqlconn);
SqlDataReader res = cmd.ExecuteReader();
while (res.Read())
{
GiacenzeMobile giac = new GiacenzeMobile();
giac.IdGiacenza = res.GetInt32(0);
//..... set all data ...
giacenzeMobile.Add(giac);
}
return giacenzeMobile;
}
}
And this is the controller (.cs):
public class GiacenzeMobileController : ApiController
{
[Route("api/giacenzemobile/getGiacenze")]
public IEnumerable<GiacenzeMobile> GetGiacenze()
{
return GiacenzeMobile.EstraiGiacenzeMobile();
}
//...other code...
}
And this is the result write on the console log:
Array(6)0: {}1: {}2: {}3: {}4: {}5: {}
SOLVED
I didn't set as public the fields of the GiacenzeMobile object.
If your attributes are private kotlin will not add it to the JsonString when it is deserialized. So make them public or remove the private identifier
Related
I have Win Forms Application with Chromium. My goal is getting string variable (json), witch had generated at C# land, for using with javascript function. I can't get it at javascript-land.
I created mefod getJSON() at JSObj.cs - it generated json. And I saw string from method. I registered oblect JSObj at Form1.cs (here I have Chromium). I called JSObj.getJSON() from html with button, but I didn't json in javascript code!
<button class="btn btn-info" id="btn3">Test Winform Interaction</button>
$("#btn3").on('click', function () {
alert(jSObject.getJSON()[0]);
});
public string getJSON()
{
DispHandler hand = new DispHandler(delegate
{
string directoryPath = #"C:\";
List<SObject> sendObjects = new List<SObject>();
DirectoryInfo directoryInfo = new DirectoryInfo(directoryPath);
FileInfo[] filesArray = directoryInfo.GetFiles();
foreach (var el in filesArray)
{
sendObjects.Add(new SObject(el.Name, directoryPath));
}
string json = JsonConvert.SerializeObject(sendObjects);
return json;
});
IAsyncResult resultObj = hand.BeginInvoke(null, null);
var res = hand.EndInvoke(resultObj);
return res;
}
public Form1()
{
InitializeComponent();
InitializeChromium();
_browser.RegisterAsyncJsObject("jSObject", new JSObj());
}
It was no errors. I expect getting json data in javascript-land.
Communication between C# and CEF is asynchronous, jSObject.getJSON() returns a Promise to result, not result itself. Try this JS code:
$("#btn3").on('click', function () {
jSObject.getJSON().then(function (r) { alert(r[0]); });
});
How can I get data from Cloud onCall() function to Android client and use it in a java code?
The client connects to function and function connects to firestore. But I can`t get data back from the function to client. I know that data has json format. But how to pass data to android, and how to use this data in android code (for example to setText in TextView).
java onClick() method:
onClick(){
String first = editTextTitle.getText().toString();
String second = editTextDescription.getText().toString();
//Here I try to setText received from function, but nothing happen.
tv_function.setText(function_3(first, second).toString());
}
java - call function:
private Task<String> function_3(String first, String second) {
mFunctions = FirebaseFunctions.getInstance();
Map<String, Object> data = new HashMap<>();
data.put("text", first);
data.put("push", second);
return mFunctions
.getHttpsCallable("sendMessageToAndroid")
.call(data)
.continueWith(new Continuation<HttpsCallableResult, String>()
{
#Override
public String then(#NonNull Task<HttpsCallableResult> task) throws
Exception {
String result = (String)task.getResult().getData();
return result;
}
});
}
javaScript function:
exports.sendMessageToAndroid = functions.https.onCall((data, context) => {
var batono = {
first: data.fara,
second: data.mina
}
return db.collection('abra-codabra').doc("mu-mu").set(batono)
.then(()=>{
var arba = {
aram:"aramando",
borem:"boremuno"
}
return arba;
});
});
How to get var "arba" to AndroidStudio and set it to TextView?
By doing
Map<String, Object> data = new HashMap<>();
data.put("text", first);
data.put("push", second);
return mFunctions
.getHttpsCallable("sendMessageToAndroid")
.call(data)
...
(as shown in the example from the documentation) you send to your Callable Cloud Function a map with a text element.
However, in your Cloud Function code you do:
var batono = {
first: data.fara,
second: data.mina
}
So, it means that you should send a map with the following elements: fara and mina, not a map with text (or you would have done something like var batono = {text: data.text}).
So, you should most probably do something like the following (not tested however):
Map<String, Object> data = new HashMap<>();
data.put("fara", .....);
data.put("mina", .....);
data.put("push", true);
return mFunctions
.getHttpsCallable("sendMessageToAndroid")
.call(data)
...
What is the best way to return a value of a method of rest service ? A java object, json string or with Response?
For example, these examples are implemented with api jersey (maven):
1) Return java object (mapped to json):
#GET
#Path("/getUser")
#Produces({MediaType.APPLICATION_JSON})
public UserVO getUser() {
UserVO user = new UserVO();
user.setValid(true);
user.setName("Peter");
return user;
}
2) Return a json string:
#GET
#Path("/getUser")
public String getUser() {
UserVO user = new UserVO();
user.setValid(true);
user.setName("Peter");
Gson gson = new Gson();
String jsonResp = gson.toJson(user);
return jsonResp;
}
3) Return with response json:
#GET
#Path("/getUser")
public Response getUser() {
UserVO user = new UserVO();
user.setValid(true);
user.setName("Peter");
Gson gson = new Gson();
String jsonResp = gson.toJson(user);
return Response.ok(jsonResp, MediaType.APPLICATION_JSON).build();
}
What is the difference between these 3? Which is better to use ?
(Considering it will be consumed from javascript)
All three options seem valid, but the first one is in my opinion more consistent because you're using an API (jersey) and this #produces annotation is the common way to use that API.
Moreover it won't make you dependant of another lib, GSON, which you could ultimately remove from your classpath if it isn't used elsewhere.
I'm trying to send some datas from the controller to the jsp view then parse them using javascript to fill a table in html
this is the controller's method
final String SERVER_URI = "http://localhost:8081/BackEndFinalVersion";
#RequestMapping(value = "/CourriersArrivées", method = RequestMethod.GET)
public String showHome(Principal principal,Model model) {
RestTemplate restTemplate = new RestTemplate();
#SuppressWarnings("unchecked")
Map<String, Object> roles = restTemplate
.getForObject(SERVER_URI + "/getUserRole" + "?uid=" + principal.getName(), HashMap.class);
List<String>r=(List<String>) roles.get("roles");
for (int i = 0; i < r.size(); i++) {
if(r.get(i).equals("Secrétaire Générale")){
#SuppressWarnings("rawtypes")
List<Map<String, Object>> allCourrier= restTemplate.getForObject(SERVER_URI + "/listCourriersArrivés", ArrayList.class);
System.out.println(allCourrier);
model.addAttribute("allCourrier", allCourrier);
return "CourriersArrivées";
}
}
return "CreationCourrier";
}
this controller will redirect me to "CreationCourrier.jsp page with the "allCourrier" attribute which is a List<Map> which gives me a result like this
[{date=19-5-5, expéditeur=Steg, listePiécesJointes=[C:\Users\Wassim\Downloads\eclipse\compte.txt, C:\Users\Wassim\Downloads\eclipse\udemy mdp.txt], isValidated=true, idCourrierArrivéFolder=workspace://SpacesStore/6cd81e2e-512f-47a1-a372-014369368584, départmentId=ROLE_ADMIN}, {date=19-5-5, expéditeur=Steg, listePiécesJointes=[C:\Users\Wassim\Downloads\eclipse\mdp enis account.txt, C:\Users\Wassim\Downloads\eclipse\udemy mdp.txt], isValidated=true, idCourrierArrivéFolder=workspace://SpacesStore/68afae4e-195f-4d58-8d0d-3b3525b0edeb, départmentId=ROLE_ADMIN}
which is very hard to parse because it is not json so I can't parse him easily with javascript
My question is that is there any easy way to parse this result and if not can you show me how to send json format for exemple which is easier to parse
I've looked in a variety of places for an answer to my query, but nothing has helped me thus far. I'm currently trying to learn Android development, and i'm stuck on how to sort a list alphabetically. I am using this tutorial on how to create the list and have modified parts of the "Albums" page to suit my needs, from albums to artists (i'm still working on this, just wanting the sorting finished before changing it fully). This particular list calls on a file from a HTTP address when the app is accessed to check it for updates.
Here is the code from that particular page, minus all the imports:
public class AlbumsActivity extends ListActivity {
// Connection detector
ConnectionDetector cd;
// Alert dialog manager
AlertDialogManager alert = new AlertDialogManager();
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jsonParser = new JSONParser();
ArrayList<HashMap<String, String>> albumsList;
// albums JSONArray
JSONArray albums = null;
// albums JSON url
private static final String URL_ALBUMS = "http://api.androidhive.info/songs/albums.php";
// ALL JSON node names
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_SONGS_COUNT = "songs_count";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_albums);
cd = new ConnectionDetector(getApplicationContext());
// Check for internet connection
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(AlbumsActivity.this, "Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
// Hashmap for ListView
albumsList = new ArrayList<HashMap<String, String>>();
// Loading Albums JSON in Background Thread
new LoadAlbums().execute();
// get listview
ListView lv = getListView();
/**
* Listview item click listener
* TrackListActivity will be lauched by passing album id
* */
lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2,
long arg3) {
// on selecting a single album
// TrackListActivity will be launched to show tracks inside the album
Intent i = new Intent(getApplicationContext(), TrackListActivity.class);
// send album id to tracklist activity to get list of songs under that album
String album_id = ((TextView) view.findViewById(R.id.album_id)).getText().toString();
i.putExtra("album_id", album_id);
startActivity(i);
}
});
}
/**
* Background Async Task to Load all Albums by making http request
* */
class LoadAlbums extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AlbumsActivity.this);
pDialog.setMessage("Listing Artists...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Albums JSON
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
String json = jsonParser.makeHttpRequest(URL_ALBUMS, "GET",
params);
// Check your log cat for JSON reponse
Log.d("Albums JSON: ", "> " + json);
try {
albums = new JSONArray(json);
if (albums != null) {
// looping through All albums
for (int i = 0; i < albums.length(); i++) {
JSONObject c = albums.getJSONObject(i);
// Storing each json item values in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String songs_count = c.getString(TAG_SONGS_COUNT);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_SONGS_COUNT, songs_count);
// adding HashList to ArrayList
albumsList.add(map);
}
}else{
Log.d("Albums: ", "null");
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all albums
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
AlbumsActivity.this, albumsList,
R.layout.list_item_albums, new String[] { TAG_ID,
TAG_NAME, TAG_SONGS_COUNT }, new int[] {
R.id.album_id, R.id.album_name, R.id.songs_count });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
My problem is that I have no real idea where I need to put the Collections.sort command. I have tried in so many places, but cannot get it working. No matter where I put the command, it always sorts in order of ID. This is the full code I have for that:
Collections.sort(params, new Comparator<NameValuePair>() {
#Override
public int compare(NameValuePair art1, NameValuePair art2) {
//here getTitle() method return app name...
return art1.getName().compareToIgnoreCase(art2.getName());
}
});
If I try to have return art1.name.compareToIgnoreCase(art2.name); it comes back with an error that says name cannot be resolved or is not a field. I'm really stumped. I thought a list might be a good way to start learning to develop for Android, but now i'm finding this incredibly hard.
Any help would be greatly appreciated.