I can't decrypt text - c#

I have url http://translate.google.ru/translate_a/t?client=x&text=ввійти вийти&sl=ua&tl=en
If you will go through this link in response you will have js file with normal translate text:
{"sentences":[{"trans":"enter exit","orig":"ввійти вийти","translit":"","src_translit":"vviy̆ty vyy̆ty"}],"src":"uk","server_time":127}
But if you get this data through program you will have encrypt translate data:
{"sentences":[{"trans":"\u00D0 \u00B2 \u00D0 \u00B2 \u00D1-\u00D0 \u00B9 \u00D1,
\u00D0 \u00B8 \u00D0 \u00B2 \u00D0 \u00B8 \u00D0 \u00B9 \u00D1, \u00D0 \u00B8",
"orig":"\u00D0\u00B2\u00D0\u00B2\u00D1?\u00D0\u00B9\u00D1?\u00D0\u00B8 \u00D0\u0
0B2\u00D0\u00B8\u00D0\u00B9\u00D1?\u00D0\u00B8","translit":"","src_translit":""}
],"src":"is","server_time":4}
Through this code i got this data.
string url = #"http://translate.google.ru/translate_a/t?client=x&text=ввійти вийти&sl=ua&tl=en";
WebRequest request = WebRequest.Create(url);
request.Timeout = 5000;
WebResponse responce = request.GetResponse();
Stream stream = responce.GetResponseStream();
StreamReader st = new StreamReader(stream);
string responsText = st.ReadToEnd();
Console.WriteLine(responsText);
Console.ReadLine();
How can i decrypt this data?

The data is not encrypted. It is encoded. If you use proper JSON deserialization, like the DataJsonContractSerializer class, this will not be a problem, because the framework will decode the data for you.
[DataContract]
public class TranslationData {
[DataMember(Name = "sentences")]
public Sentence[] Sentences { get; set; }
[DataMember(Name = "src")]
public string Source { get; set; }
[DataMember(Name = "server_time")]
public int ServerTime { get; set; }
}
[DataContract]
public class Sentence {
[DataMember(Name = "trans")]
public string Translation { get; set; }
[DataMember(Name = "orig")]
public string Original { get; set; }
[DataMember(Name = "translit")]
public string Transliteration { get; set; }
[DataMember(Name = "src_translit")]
public string SourceTransliteration { get; set; }
}
Then use the System.Runtime.Serialization.Json.DataContractJsonSerializer class for deserialization (you have to add a reference to the System.Runtime.Serialization assembly) to read from the response stream directly:
var serializer = new DataContractJsonSerializer(typeof(TranslationData));
return (TranslationData)serializer.ReadObject(theResponseStream);
There are other ways of doing this, but this way you'll get nice typed data.

Related

Encountered unexpected character ‘<’” error serializing in DataContractJsonSerializer.ReadObject(stream)

we're sending HTTP request to Bing maps with address details to get back the address map point. The response of the HTTP request is read as stream async, this stream is then deserialized to Bing response format. When I deserialize, I'm getting this error: System.Runtime.Serialization.SerializationException : Error while deserializing the object of type Previseo.Workflows.BingResponse. Unexpected character '<'.
Your help is so appreciated.
I've used Fiddler to see the response of bings which sends it back in the form of JSON:https://i.stack.imgur.com/LPIeW.png
JSON returned as text:
{"authenticationResultCode":"ValidCredentials","brandLogoUri":"http:\/\/dev.virtualearth.net\/Branding\/logo_powered_by.png","copyright":"Copyright © 2019 Microsoft and its suppliers. All rights reserved. This API cannot be accessed and the content and any results may not be used, reproduced or transmitted in any manner without express written permission from Microsoft Corporation.","resourceSets":[{"estimatedTotal":1,"resources":[{"__type":"Location:http:\/\/schemas.microsoft.com\/search\/local\/ws\/rest\/v1","bbox":[46.175388336181641,5.1528801918029785,46.231620788574219,5.28734016418457],"name":"01000, Ain, France","point":{"type":"Point","coordinates":[46.203506469726563,5.2217612266540527]},"address":{"adminDistrict":"Auvergne-Rhone-Alpes","adminDistrict2":"Ain","countryRegion":"France","formattedAddress":"01000, Ain, France","locality":"Bourg-en-Bresse","postalCode":"01000"},"confidence":"High","entityType":"Postcode1","geocodePoints":[{"type":"Point","coordinates":[46.203506469726563,5.2217612266540527],"calculationMethod":"Rooftop","usageTypes":["Display"]}],"matchCodes":["Good"]}]}],"statusCode":200,"statusDescription":"OK","traceId":"e1464a431e5e46b9854053ed8ae76ba8|DU00000D78|7.7.0.0|Ref A: 865592F3CBB74AD6ADA8A71D8344F297 Ref B: DB3EDGE0817 Ref C: 2019-08-07T07:56:20Z"}
private MapPoint GetAddressMapPoint(string address, string ville)
{
int idx;
string postal, city, url;
HttpClient client;
HttpResponseMessage apires;
DataContractJsonSerializer jsonSerializer;
BingResponse bingResp = null;
idx = ville.IndexOf(" ");
postal = ville.Substring(0, idx);
city = ville.Substring(idx + 1);
url = BING_MAPS_BASE_ADDRESS + $"REST/v1/Locations/FR/{postal}/{city}/{address.Trim()}?key={BingMapsKey}";
client = new HttpClient();
apires = client.GetAsync(url).Result;
jsonSerializer = new DataContractJsonSerializer(typeof(BingResponse));
Stream stream = apires.Content.ReadAsStreamAsync().Result;
bingResp = (BingResponse)jsonSerializer.ReadObject(stream); //here is where I'm getting the error 'Unexpected caracter '<'
if (bingResp.resourceSets.Count > 0)
{
if (bingResp.resourceSets[0].resources.Count > 0)
{
var point = bingResp.resourceSets[0].resources[0].point;
return point;
}
}
return null;
}
public class BingResponse
{
[DataMember]
public string authenticationResultCode { get; set; }
[DataMember]
public string brandLogoUri { get; set; }
[DataMember]
public string copyright { get; set; }
[DataMember]
public List<ResourceSet> resourceSets { get; set; }
[DataMember]
public int statusCode { get; set; }
[DataMember]
public string statusDescription { get; set; }
[DataMember]
public string traceId { get; set; }
}

Read specific object data from json

I want to get specific object data from json from url the following code give me. i need the second object 'EmailAddressSuffices'
WebRequest request = WebRequest.Create(
"https://atea-dev.accesscontrol.windows.net/v2/metadata/IdentityProviders.js?protocol=wsfederation&realm=https%3a%2f%2flocalhost%3a44300%2fAccount%2fLoginCallback%2f&reply_to=https%3a%2f%2flocalhost%3a44300%2fAccount%2fLoginCallback%2f&context=&request_id=&version=1.0&callback=");
request.Credentials = CredentialCache.DefaultCredentials;
WebResponse response = request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
Using JSON.Net you can deserialize the JSON response easily:
Solution 1
1. Create a class to map your JSON into:
public class ResponseObject
{
[JsonProperty("Name")]
public string Name { get; set; }
[JsonProperty("LoginUrl")]
public string LoginUrl { get; set; }
[JsonProperty("LogoutUrl")]
public string LogoutUrl { get; set; }
[JsonProperty("ImageUrl")]
public string ImageUrl { get; set; }
[JsonProperty("EmailAddressSuffixes")]
public IList<string> EmailAddressSuffixes { get; set; }
}
2. Deserialize your JSON using JsonConvert.Deserialize<ResponseObject>()
var myresponse = JsonConvert.DeserializeObject<List<ResponseObject>>(responseFromServer);
string email = myresponse[1].EmailAddressSuffixes[0];
Solution 2
If you don't want to bother with derializing the entire thing then you can do this:
JArray array = JArray.Parse(responseFromServer);
string q = array[1]["EmailAddressSuffixes"][0].ToString();
But you should make sure that your object has the right format (and the right number of items in the array.

The header of response web service in c#

The format of response
adbc91a43e988a3b5b745b8529a90b61
<RESPONSE Stamp="YYYY-MM-DDTHH:MM:SSZ" RE="…" ERR_TEXT="…">
<PaymentID>3242343</PaymentID>
</RESPONSE>
The first line of the response consists of a md5-hash xml-response + parameters hash, followed by
xml-response.
The main element of xml-response is called RESPONSE...
How and where to add the hash code?
Thanks
I have XML without hashcode. My code in c#
[WebMethod]
public RESPONSE GET( string id)
{
RESPONSE res = new RESPONSE();
res.ERR_TEXT = "";
res.RE = "";
res.Stamp = DateTime.Now.ToString("yyyy-MM-ddthh-mm-ssz");
res.PaymentID = id;
return res;
}
public class RESPONSE
{
[XmlAttribute]
public string ERR_TEXT { get; set; }
[XmlAttribute]
public string RE { get; set; }
[XmlAttribute]
public string Stamp { get; set; }
public string PaymentID { get; set; }
}
In output get only XML. But must still pass the hash code.
I must send a response to a client request. And they want that at response body was hash and xml. And how it should look like I can not understand.

How to parse multiple records in Json

Hello I am trying to parse a Json response into a class. So here is how the response looks...
[{"id":103,"customer_id":0},{"id":110,"customer_id":1}]
I was able to parse one line okay (I removed the '[' ']' and put it into one class). The problem is when I have multiple records, like this, that I am having an issue. This is how I am parsing the data...
[DataContract]
public class Order
{
public List<OrderRow> Orders { get; set; }
}
[DataContract]
public class OrderRow
{
[DataMember(Name = "id")]
public int id { get; set; }
[DataMember(Name = "customer_id")]
public int customer_id { get; set; }
}
StreamReader jfile = new StreamReader(#"path\test.json");
string json = jfile.ReadToEnd();
jfile.Close();
byte[] bytes = Encoding.UTF8.GetBytes(json);
MemoryStream mStream = new MemoryStream(bytes);
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Order));
Order jsonOrder = (Order)serializer.ReadObject(mStream);
Instead of creating Order class, try to deserialize it directly into OrderRow[] array:
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(OrderRow[]));
OrderRow[] jsonOrderRows = (OrderRow[])serializer.ReadObject(mStream);

Metro App - deserialize JSON String

I'd like to deserialize a JSON string which I get from a webservice. My problem is, that the deserialized object class array (of type Result) has always 0 items in it....
But the webservice returns the correct string.
So I think the failure occurs in the way how I deserialize the string/stream.
Any ideas what's my fault?
//JSON result string:
{"Results":
[{"Result":{
"Name":"Rechnung2",
"Date1":"2012-10-05",
"Item1":"50",
"Item2":"10",
"CompanyName":"Contoso",
"Description":"My description"}}]
}
[DataContract]
public class Result
{
[DataMember]
public string Name { get; set; }
[DataMember]
public string Date1 { get; set; }
[DataMember]
public string Item1 { get; set; }
[DataMember]
public string Item2 { get; set; }
[DataMember]
public string CompanyName { get; set; }
[DataMember]
public string Description { get; set; }
}
public async void GetjsonStream()
{
HttpClient client = new HttpClient();
string url = "http://localhost/test/api.php?format=json&key=12345";
HttpResponseMessage response = await client.GetAsync(url);
//ReadAsStringAsync() works fine, so I think ReadAsStreamAsync() works also fine
var str = await response.Content.ReadAsStreamAsync();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Result[]));
//Result has always 0 items
Result[] res = (Result[])ser.ReadObject(str);
}
I haven't used DataContractJsonSerializer myself, so this may not be the best approach - but I suspect that the problem is that the JSON represents "an object containing a collection of results" - not "a collection of results".
Try this, in addition to your existing code:
[DataContract]
public class ResultCollection
{
[DataMember]
public Result[] Results { get; set; }
}
...
var ser = new DataContractJsonSerializer(typeof(ResultCollection));
var collection = (ResultCollection)ser.ReadObject(str);
var results = collection.Results;
You may be able to change the type of Results to List<Result> too, if that's helpful.
(I've just tried the code above, and it gave me the right result, so it looks like this is at least along the right lines...)

Categories