How to deserialize the body of a brokered message in node js? - json

I am implementing socket.io server in node js (socketio.js) for my windows azure project. My worker role is in c#. And am sending a brokered message from worker role to socketio.js through service bus queue. But The object which am sending through the brokered message is not getting serialized into a json object. I dont know how to access the body of this brokered message in node js.
I can show how am sending the brokered message in the worker role and how am receiving it in the node js script.
The response body of brokered message(i.e message.body)
#rrayOfTestModelHhttp://schemas.datacontract.org/2004/07/Project.Model ☺i)http://www.w3.org/2001/XMLSchema-instance☺
TestModel is the name of the object model which am sending through the brokered message body.
Worker Role:
BrokeredMessage socketioMessage = new BrokeredMessage(messageObject);
WorkerRoleClient.Send(socketioMessage );
Node Js script:
serviceBusService.receiveQueueMessage(queue, function (error, receivedMessage) {
if (!error) {
console.log(receivedMessage);
if (receivedMessage != null) {
var messageBody = receivedMessage.body;
console.log(messageBody);
io.sockets.emit('news', messageBody);
}}
the message body i receive here is some plain unreadable string. And i am sending proper objects from the worker role. Please let me know if any of you have an idea about whats going wrong
Thanks

I finally found a way to de serialize it and getting the json objects.
Worker Role in C#
var recordsMessage = Newtonsoft.Json.JsonConvert.SerializeObject(data);
BrokeredMessage socketMessage = new BrokeredMessage(recordsMessage);
Receiving in Node js:
if (receivedMessage != null) {
var messageBody = receivedMessage.body;
var jsonString = messageBody.substring(messageBody.indexOf('['), messageBody.indexOf("]")+1);
var recordsQueue = JSON.parse(jsonString);
}
Hope this helps someone

I know it's an old ticket but i guess it might help people in the future as it helped me today :).
Instead of using substring from your nodejs app, you have the possibility to directly send the message in string without the automatic serialization.
To do so, use the following code :
using (Stream stream = new MemoryStream())
using (TextWriter writer = new StreamWriter(stream))
{
writer.Write("Start");
writer.Flush();
stream.Position = 0;
queueClient.Send(new BrokeredMessage(stream) { ContentType = "text/plain" });
}
Hope it will help,
Clément

I am also trying to find a reference to help doing this, please check the following link: http://www.rackspace.com/blog/node-swiz-node-js-library-for-serializing-deserializing-and-validating-objects-in-rest-apis/
it shows the serialization and the deserialization using Node JS in any of the requested format (JSON or XML)
let me know if this work with you :)

Related

HttpClient reads incomplete or malformed string

Im trying to figure out which part of my app (Xamarin Forms and proxy written in PHP) is buggy. Firstly I thought that my proxy (written in PHP) is working incorrectly with long set of data (ie. json containing 1.300.000 characters) and returns malformed response, but every single request with Postman gives me correct JSON, which is successfully decoded with third-party tools. So I assume, proxy is working well.
The problem is (I guess) with decoding response in my Xamarin Forms (2.0.0-beta.22) app. I'm using HttpClient to read response with this code:
response.EnsureSuccessStatusCode();
var entries = new List<HistoryEntry>();
var content = await response.Content.ReadAsStringAsync();
_loggerService.Error(content);
response is just GetAsync response from HttpClient. The problem is: content is randomly incomplete/malformed. Saying this I mean last character is missing (}) or JSON keys/values have additional " character, which breaks everything. Unfortunately, I can make exactly the same requests many times and once it works, once not. I found out that this behavior happens only with large set of data (as I mentioned before, long JSON string).
Is there any possibility that ReadAsStringAsync does not wait for full response or in any way alters my response string? How can I find the reason of wrongly downloaded data?
EDIT 21.05.2019:
Just copied valid JSON (available here: https://github.com/jabools/xamarin/blob/master/json.txt) and returned it from Lumen app by response()->json(json_decode(..., true)) and still the same result. Hope someone will be able to reproduce this and help me with this issue :( More informations in comments.
Used this code in C#:
Device.BeginInvokeOnMainThread(async () =>
{
for (int i = 0; i < 10; i++)
{
var response = await client.GetAsync("<URL_TO_PHP>");
//var response = await client.GetAsync("https://jsonplaceholder.typicode.com/photos");
var content = await response.Content.ReadAsAsync<object>();
Debug.WriteLine("Deserialized: " + i);
}
});

Unable to access data inside a string (i.e. [ object Object ]) that was originally sent as a JSON object

I'm using axios to send a JSON object as a parameter to my api. Before it post request is fired, my data starts of as a JSON object. On the server side, when I console.log(req.params) the data is returned as such
[object Object]
When I used typeof, it returned a string. So then I went to use JSON.parse(). However, when I used that, it returned an error as such
SyntaxError: Unexpected token o in JSON at position 1
I looked for solutions, but nothing I tried seemed to work. Now I'm thinking I'm sending the data to the server incorrectly.
Here's my post request using axios:
createMedia: async function(mediaData) {
console.log("SAVING MEDIA OBJECT");
console.log(typeof mediaData)
let json = await axios.post(`http://localhost:3001/api/media/new/${mediaData}`)
return json;
}
Any thoughts on how I can solve this?
You need to update your code using axios to provide the mediaData in the body of the request instead of the URL:
createMedia: async function(mediaData) {
console.log("SAVING MEDIA OBJECT");
console.log(typeof mediaData)
let json = await axios.post(`http://localhost:3001/api/media/new/`, mediaData)
return json;
}
In the backend (assuming you're using express here), you need to configure your application to use bodyParser:
var express = require('express')
, app = express.createServer();
app.use(express.bodyParser());
And then in your controller update your console.log(req.params) to console.log(req.body); then restart your node server

What is the efficient way to get the fields from this JSON object?

I've the following code that returns json object. And I need to filter sender email, subject, and creationDate. The code does the job but I felt like there is an efficient way to do it. I appreciate your suggestion.
ResponseEntity<String> response =
restTemplate.exchange(app.getResourceUrl() + personnelEmail+
MESSAGE+"/?$select=Sender,Subject,CreatedDateTime", HttpMethod.GET, request, String.class);
String str=response.getBody();
JSONObject jsonObject= new JSONObject(str);
JSONArray arrayList= (JSONArray)jsonObject.get("value");
List l=arrayList.toList();
for(int i=0;i<l.size();i++){
HashMap<String,HashMap> hashMap=(HashMap<String,HashMap>)l.get(i);
HashMap<String,HashMap> sender= hashMap.get("sender");
HashMap<String,String> senderEmail= sender.get("emailAddress");
String email= senderEmail.get("address");
}
Here is the json object I receive from MS Office API.
{"#odata.context":"https://graph.microsoft.com/v1.0/$metadata#users('user34.onmicrosoft.com')/messages(sender,subject,createdDateTime)","value":[{"#odata.etag":"W/\”sljkasfdiou7978klosadf\"","id”:"lkjasdfu97978KLJASDFS_WGHJJ76J897DKdcuvtymBTItq836K34PUAAAvoK3SAAA=","createdDateTime":"2016-08-27T04:07:08Z","subject":"View
your Office 365 Enterprise E3 billing
statement","sender":{"emailAddress":{"name":"Microsoft Online Services
Team","address”:"T45763#email.microsoftonline.com"}}},{"#odata.etag":"W/\”JUU70303\"","id”:”UEYO93988FK;O38GV3J884=","createdDateTime":"2016-08-26T15:28:47Z","subject":"Order
confirmation: Thank you for your
purchase","sender":{"emailAddress":{"name":"Microsoft Online Services
Team","address":"obue733#email.microsoftonline.com"}}},{"#odata.etag":"W/\”LJKOIU987983\"","id”:”ladjksflk83l.x8783LKFW3=","createdDateTime":"2016-06-24T03:03:26Z","subject":"Attention:
Your Microsoft Azure Active Directory Premium trial subscription will
be disabled soon","sender":{"emailAddress":{"name":"Microsoft Online
Services Team","address":"635cdeee#email.microsoftonline.com"}}}]}
By default Office 365 REST API response payload also includes common annotations such as:
odata.context: the context URL of the payload
odata.etag: the ETag of the entity, as appropriate
The below picture demonstrates it
As you've already might guessed it could be controlled via odata.metadata parameter:
The odata.metadata parameter can be applied to the Accept header of
an OData request to influence how much control information will be
included in the response.
Example (C# version)
The example demonstrates how to set odata.metadata=none format parameter via Accept header to indicate that the service SHOULD omit control information
using (var client = new HttpClient(handler))
{
var url = "https://outlook.office365.com/api/v1.0/me/messages?$select=Sender,Subject,DateTimeCreated";
client.DefaultRequestHeaders.Accept.Add(MediaTypeWithQualityHeaderValue.Parse(GetMediaType("none",false,false)));
var result = await client.GetStringAsync(url);
var data = JObject.Parse(result);
foreach (var item in data["value"])
{
//process item;
}
}
where
private static string GetMediaType(string metadata,bool streaming,bool IEEE754Compatible)
{
return String.Format("application/json; OData.metadata={0}; OData.streaming={1}; IEEE754Compatible={2}",metadata,streaming, IEEE754Compatible);
}

Sending data from Dart to PHP using POST method

I am trying to send some data from Dart to PHP...
This is the code i am using to send the data from Dart:
button.onClick.listen((e) {
var req = new HttpRequest();
req.onReadyStateChange.listen((HttpRequestProgressEvent e) {
if (req.readyState == HttpRequest.DONE) {
print('Data submitted!');
}
});
req.open('POST', form.action);
req.send('hello from dart');
});
In my PHP file I am trying to use the string i have send from dart, but count($_POST) returns 0. $_POST seems to be empty...
Dart code DOES trigger the php script and 'Data submitted' is printed...
This is actually related to your PHP configuration. You can access the POST'd data with PHP's reserved variable: $HTTP_RAW_POST_DATA However the preferred method is to use php://input
I am very new to Dart, but you can use FormData in the send. So a quick and dirty way could be.
var data_form = new FormData(query('#My_form'));
button.onClick.listen((e){
var request = new HttpRequest():
request.open('POST', 'http://Localhost/form_data.php');
request.send(data_form);

json rpc client for services module drupal

I am trying to create a json rpc client to access drupal services provided by services module for titanium.
function connect()
{
var loader = Titanium.Network.createHTTPClient();
var url = "http://10.0.2.2/service/services/json";
loader.open("POST",url);
loader.onload = function()
{
alert(this.responseText);
};
loader.send({"method:'system.connect'"});
}
This code results saying 'invalid method'.
I think the parsing of the data is not in the correct format.
Please help to resolve this problem.
Update your code like this :
loader.send({method:'system.connect'});
Refer Working with JSON Data in Drupal for more details .