How i send a object from Java like a Javascript object? - javascript

I have an application Angular 7 frontend, Android mobile and a Laravel backend. I send an object in Angular 7 that is working fine on Laravel this is the object
{
"mov_entry_id": 72507,
"limitHour": "02/07/2019 13:40:27",
"plate": null,
"mov_vehicle_id": 1,
"mov_vehicle_name": "Carro",
"value": "8.00",
"mov_area_id": 7,
"mov_area_name": "AB",
"mov_user_id": 1,
"validated": "N",
"updated_at": "02/07/2019 13:20:27",
"mov_entry_ean13": "7800000725070",
"created_at": "02/07/2019 13:20:27"
}
I'm sending a post method from angular to laravel this is the backend part that receive this object
$entryObj = $request->input('entry');
$userid = $request->input('userid');
$hourValue = 0;
$validatedDate;
$response["success"] = 1;
$response["message"] = "Entrada validada com blabla";
$response['entryObj'] = $entryObj;
$response['mov_entry_ean13'] = $entryObj["mov_entry_ean13"];
return $response;
I get the object in "$request->input('entry');" in this part and I want to access the object like this $entryObj["mov_entry_ean13"];, when I send in Angular 7 with the Json as I show to you guys, my Laravel application access this is object fine, but my problem is on Android.
When I use Java in Android, I tried to make the object looks like the javascript way but with no success, I try JsonObject, JsonElement, and Map, this is my Retrofit API:
#FormUrlEncoded
#POST("/api/validateentrymobi")
public Call<JsonObject> validateTicket(
#Field("entry") JsonObject entry,
#Field("userid") String user_id
);
When I use I'm getting this error "Illegal string offset "mov_entry_ean13"", like is something wrong with my object that I'm sending, this is the object from java
{"mov_entry_id":72507,"plate":null,"mov_vehicle_id":1,"mov_vehicle_name":"Carro","value":"8.00","mov_area_id":7,"mov_area_name":"AB","mov_user_id":1,"validated":"N","mov_entry_ean13":"7800000725070","created_at":"02/07/2019 13:20:27","updated_at":"02/07/2019 13:20:27","validated_date":"2019-07-02 13:40:27"}
What I'm doing wrong?

You need to create a POJO and set up a json converter for Retrofit to use.
Setup Retrofit
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create()) // this requires implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
.build()
Create a POJO class annotated with Gson
// this will act as the top level json object {}
class MyBody {
#SerializedName("mov_entry_id")
int movEntryId;
// write your fields here
}
Use the POJO as the body for Retrofit request
// you don't need the form unless your backend requires it
#POST("/api/validateentrymobi")
public Call<ResponseBody> validateTicket( // #NOTE the return type, you can create a POJO class similar to how I created MyBody and replace ResponseBody with it. But ResponseBody should work.
#Body MyBody myBody
);

Related

How to send Object in a multipart/form-data request without converting to string in Angular

I have to pass the object in "multipart/form-data" request so that it can be received in downstream application (Java Spring) as List i.e custom class object. Metadata object contains only key and value
In Angular
interface Metadata{
key:string;
value:string;
}
In Angular I am using FormData to create the multipart request as given below.
metadatas = new Array<Metadata>();
// few values added in metadatas array.
fileToUpload: File ; // contains file information
const formData: FormData = new FormData();
formData.append('file', fileToUpload, fileToUpload.name);
formData.append('metadata',JSON.stringify(this.metadatas))
As FormData append method definition says the "value: string | Blob" so I need to convert my metadatas object to string using JSON.stringify().
But when I do so in Spring application (downstream), I can receive the object in String e.g
#PostMapping(path = "/file-upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<String> fileUpload(
#RequestParam(name = "metadata", required = false) String metadata,
#RequestParam(name = "file", required = false) MultipartFile file) {
System.out.println(metadata);
System.out.println(file);
return new ResponseEntity<>("example", HttpStatus.OK);
}
Above code is working and able to get the metadata and file data, but as my API says it should be received in Java Object. So my spring method definition it should be List. Again here the metdata is the object contain key and value.
In Java
public class Metadata {
private String key;
private String value;
// getter and setters
}
In below code the metadata should be capture in List
#PostMapping(path = "/file-upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<String> fileUpload(
#RequestParam(name = "metadata", required = false) List<Metadata> metadata,
#RequestParam(name = "file", required = false) MultipartFile file) {
System.out.println(metadata);
System.out.println(file);
return new ResponseEntity<>("example", HttpStatus.OK);
}
I tried varies things with #RequestPart and #RequestParam, but nothing is working out. As per my understanding, I think that as I am converting the metadata in string while sending from angular hence I am able to received it in String object.
But in FormData I don't have any option to append the object directly as it allows string or Blob. Is there any other way to send the multipart object without converting to string in angular?
Or even if we send the object using FormData how we can received the object in Java Class i.e. List in Spring Boot Application ?
Please help me for getting the solution with the detail explanation as I am new to this.
What is working out for me is:
#PostMapping("/upload_pic")
fun uploadPic(#RequestParam(IMAGE) image: MultipartFile?,
#RequestParam(GROUP_ID) groupId: String,
#RequestHeader(DEVICE_ID_HEADER_STRING) deviceId: String,
#RequestHeader(TOKEN_HEADER_STRING) authToken: String): ResponseEntity<StatusModel> {
All the annotation parameters are String constants.
BTW, this is in kotlin.

PUT Method payload for REST Webservice

I have object as
{
"sch": {
"name":"ABC",
"time_zone":"Eastern Time (US & Canada)",
....
}
}
I am trying to create payload for PUT method of REST web-service using javascript. I have created payload as:
var body={"sch.name":"CAD"};
but i am not able to update the name with new value CAD .
Am i doing this correctly for the "name" element?

converting JSON object in spring MVC

in the example below i have one method sendJsonResponce method which is nothing but the putting string values to Map and we are returning that map from createChildSalesPosition method to our webpage.
we are using Spring MVC here, as i have gone through some websites saying that you need to change the object to JSON type when you want to send a JSON response but in my project i find this which is sending JSON response without any type conversion in JSON.
since the guy who had developed the application is no more available i got stuck here.
#RequestMapping(value="createChildSalesPositions.json",produces="application/json")
#ResponseBody
public Map<String,String> createChildSalesPositions(#RequestParam("tId") Integer templateId,#RequestParam("prnSalesPosId") Long prnSalesPosId,#RequestParam("prnSalesHierId") Long prnSalesHierId,
HttpServletRequest request,#ModelAttribute("ALIGNMENTINFO") AlignmentInfo alignmentInfo,#ModelAttribute("USERSESSION") UserDetails userDetails)throws BusinessException, IOException{
try{
return sendJosnResponse(crId);
}
}catch(Exception e){
return sendErrorResponse(e);
}
}
private Map<String,String> sendJosnResponse(long crId) throws IOException{
Map<String,String> tosend =new HashMap<String,String>();
tosend.put("code", "200");
tosend.put("message", "CR "+crId+" has been generated successfully.");
tosend.put("crId", String.valueOf(crId));
return tosend;
}
You need to tell the spring framework how to convert the java object to json. The spring framework uses HttpMessageConverter to do that, to convert the java object to json spring can use the jackson libraray.
To enable this support you can either use the #EnableWebMvc annotation or <mvc:annotation-driven/> xml configuration and add the jackson library to your classpath.

Creating a dynamic JSON from C# to JavaScript

I am new at C# programming and I am developing an application based on geolocation for my Graduate.
I have a Javascript which is responsible for creating the map and inserting the markers. But the markers are inserted from a JSON file, like this:
{
"Id": 1,
"Latitude": -19.212355602107472,
"Longitude": -44.20234468749999,
"Descricao": "Conteúdo do InfoBox 1"
},
And after that. they call this file by this:
function carregarPontos() {
$.getJSON('js/pontos.json', function(pontos) {
$.each(pontos, function(index, ponto) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(ponto.Latitude, ponto.Longitude),
title: "Meu ponto personalizado! :-D",
map: map
});
});
});
}
carregarPontos();
My problem is I need to have those points from MySql DB.
I created a DataTable where I have the information I need to pass to this JSON, but I don't have any clues regarding how to make it.
Any help? Please keep in mind I am a noob at C# and JSON programming.
While the standard C# library offers some JSON support, you're better off using the free JSON.Net library from Newtonsoft. You can add it to your project in Visual Studio through the NuGet package manager (Project > Manage NuGet packages).
Then make sure your file has:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
To parse a JSON, just write dynamic json = JObject.Parse(str);
Then you can access its properties just like you would in JavaScript, the only difference being that undefined properties will return null.
dynamic json = JObject.Parse("{example: \"Hello world\"}");
Console.Write(json.example); // prints "Hello world"
To write a JSON, just create a JObject and then append strings, numbers, JArrays and JObjects to it.
dynamic json = new JObject();
json.example = "Hello world";
json.myArray = new JArray(1, 2, 3, 4);
Console.Write(json);
// {
// "example": "Hello world",
// "myArray": [
// 1,
// 2,
// 3,
// 4
// ]
// }
as far as I understand you have some data stored in your sql database from where you will fetch the data and pass to a javascript function.
If that is the case then you can refer to this link.
Pass json/javascript data/objects to c# function using ajax
The example given is using aspx approach and not the MVC but it will be similar.

Serialize MVC model to JSON

I am trying to do a very simple task: get an MVC model, and send it back to server as JSON. I tried
#Html.Raw(Json.Encode(Model));
When debugging the JS, I see that the date objects on the serialized JSON look like: /date (00064321)/ and when passing the serialized JSON to the server, the dates are null on the server-side. Anyone understand what is going on?
Instead of JSON encoding the model directly you have to create an anonymous object converting the date-time properties to strings.
Ex.
var meeting = new Meeting
{
Name = "Project Updates",
StartDateTime = DateTime.Now
};
Passing directly the model..
#Html.Raw(Json.Encode(meeting))
produces
{"Name":"Project Updates","StartDateTime":"\/Date(1338381576306)\/"}
and
#Html.Raw(Json.Encode(new {
Name = meeting.Name,
StartDateTime = meeting.StartDateTime.ToString()
}))
produces
{"Name":"Project Updates","StartDateTime":"5/30/2012 6:09:36 PM"}
as expected.

Categories

Resources