Porting code from Android to Windows Phone - c#

I am searching for the similar C# code for android code for below part.
atttemptMappingD is an object.
Enumeration<?> keysE = (Enumeration<?>) ((JSONObject) atttemptMappingD)
.keys();
while (keysE.hasMoreElements()) {
String key = (String) keysE.nextElement();
String value = ((JSONObject) atttemptMappingD).getString(key);
}
can anyone please suggest me how I will achieve this in C#.
for JSONObject I am using Newtonsoft.Json.Linq.JObject

LINQ to JSON is an API for working with JSON objects. It has been designed with LINQ in mind to enable to quick querying and creation of JSON objects. LINQ to JSON sits under the Newtonsoft.Json.Linq namespace. You can have Full Refrence from here(LINQ to JSON) how it can be done as per your Requirements.

I got the answer, hope this will help for someone.
var keysE = ((JObject)atttemptMappingD).ToObject<Dictionary<string, object>>();
foreach (var item in keysE)
{
string key = (string)item.Key.ToString();
string value = ((JObject)atttemptMappingD)[key].ToString();
}

Related

Parse the JSON string in the ASP.NET

I mostly work on the PHP , recently have switched to ASP.NET,
When parse the JSON, I can simply use -> to get the field, e.g.
foreach(json_decode($_POST['mandrill_events']) as $event) {
$event = $event->event;
$email_type = $event->msg->metadata->email_type;
}
However, in ASP.NET , there is no action, this is my attempt code
var post_data = Request.Form["mandrill_events"];
JavaScriptSerializer ser = new JavaScriptSerializer();
var post_data_json = ser.Deserialize<Dictionary<string, string>>(post_data);
foreach (var event_obj in post_data_json) {
//how to parse the event_obj?
}
Thanks a lot for helping.
use Newtonsoft Json.NET
JsonConvert.DeserializeObject<DataModel>(json);
Unless you want to write a C# class that represents the JSON you are POSTing (the safest solution), you can use the dynamic type to create an object which will look like your JSON. You can then do something like this answer to access the properties.
This solution doesn't give you type safety and the DLR will resolve the properties of the dynamic object at runtime.
As other answers have mentioned, your life will be made much easier by using Newtonsoft JSON which will allow you to write:
dynamic events = JsonConvert.DeserializeObject<dynamic>(post_data);
foreach(dynamic evt in events)
{
string emailType = evt.msg.metadata.email_type;
}

Search for one key in multi-level JSON array

I receive JSON output from several different web services. I need to obtain some token data from each service however it's in a different array each time. E.g.:
Service 1:
{
"service_name": "service1",
"service1_data": {
"token_data": "WSD123456789"
}
}
Service 2:
{
"service_name": "service2",
"service2_data": {
"token_data": "QSD76662345"
}
}
So I'm looking for a way to search for the value of "token_data" no matter where in the arrays it may be. At the moment I have to get it manually like so:
json1["service1_data"]["token_data"]
If theres a simple way to do this it would be much appreciated. Thanks!
You could convert the JSON to XML and then use an xpath like '//token_data' to find the token, assuming a simple string search or regex is not an option.
byte[] bytes = Encoding.ASCII.GetBytes(json);
using (var stream = new MemoryStream(bytes))
{
var quotas = new XmlDictionaryReaderQuotas();
var jsonReader = JsonReaderWriterFactory.CreateJsonReader(stream, quotas);
var xml = XDocument.Load(jsonReader);
}
Xpath info can be found here
As suggested in the comments, you could use JSONPath.
In your scenario, $.service1_data.token_data.* should get you all the values you want.
This works only if the depth of token_data in the array is always the same.
The Newtonsoft.Json package - available on NuGet Install-Package Newtonsoft.Json allows you to walk Json objects using LINQ expressions.
var jsonText = #"{
""service_name"": ""service1"",
""service1_data"": {
""token_data"": ""WSD123456789""
}
}";
var jsonObject = JsonConvert.DeserializeObject<JToken>(jsonText);
System.Diagnostics.Debug.Assert(jsonObject["service1_data"].Value<string>("token_data") == "WSD123456789");
See the JToken reference to learn how to retrieve values from Json.

How to create a json string where a property contains a dot (period)?

I'm trying to send an HttpRequest that takes a JSON object like this:
{
"some.setting.withperiods":"myvalue"
}
I've been creating anonymous objects for my other requests, but I can't do that with this one since the name contains a dot.
I know I can create a class and specify the [DataMember(Name="some.setting.withperiods")] attribute, but there must be a more lightweight solution.
There is no "easy" way to achieve this because the . in C# is reserved.
However, you could achieve something pretty close by using a dictionary and collection initializer. It's still somewhat isolated, and doesn't require you to create a custom class.
var obj = new Dictionary<string, object>
{
{ "some.setting.withperiods", "myvalue" }
};
var json = JsonConvert.SerializeObject(obj);
//{"some.setting.withperiods":"myvalue"}
You can use "JsonProperty" attribute for the same For example
[JsonProperty(".Name")]
public string Name { get; set; }
On top of this I want to add how to retrieve the data from the json where it has name property starting with special character as in Web API 2.0 token has ".issued".
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
var jsonRespons="json response from the web api";
var issue= JObject.Parse(jsonResponse).GetValue(".issued");
if you do it from in javascript, you can easily go back and forth, as shown with:
var obj = {
"some.setting.withdots":"myvalue"
};
var json = JSON.stringify(obj);
console.log(json);
var str = JSON.parse(json);
console.log(str);
have you tried putting it into a serialized string and sending that, then deserializing on the client-side?
you could do something like
var myAnnon = new
{
WithPeriod = "value"
};
var j = JsonConvert.SerializeObject(myAnnon);
j = j.Replace("WithPeriod", "some.setting.withdots");
You can use a JObject (part of Json.Net's LINQ-to-JSON API) to create the JSON in question:
string json = new JObject(new JProperty("some.setting.withperiods", "myvalue")).ToString();
Fiddle: https://dotnetfiddle.net/bhgTta
You could try prefixing your member names with a # to allow use of literals, but the way to do it is using [DataMember] as you have already mentioned in your question.

Converting JSON returned from ASMX service to list of C# objects

I am writing code to test json returned from an asmx web service in C#. The returned response is in the following format:
{"d":"[{\"Id\":\"row1\",\"TheDate\":\"01/01/2013 00:00:00\",\"Description\":\"Test1\",\"Field\":\"N\"},
{\"Id\":\"row2\",\"TheDate\":\"01/01/2013 00:00:00\",\"Description\":\"Test2\",\"Field\":\"N\"}]
Eventually, I want to convert the data as a list of objects. I'm constrained to use JSON.Net.
At the moment I am converting the json returned in the response to a JArray using the method below:
private static JArray ConvertToJsonArray(StreamReader reader)
{
var json = reader.ReadToEnd();
string result = json.Replace("{\"d\":\"", string.Empty);
result = result.Replace(#"\", string.Empty);
result = result.Replace("]\"}", "]");
return JArray.Parse(result);
}
As you can see, I am doing a lot of manual formatting of the string so that it can finally be parsed.
I then loop round and take each JObject in the JArray and convert to the required object type before adding it to a list.
This does give me the desired results but I feel that there must be a more elegant solution.
Can anyone please help?
PS - I've left a lot of code out for brevity. I can give more detail if required.
Thanks to Brian Rogers and Tanim Salem (see comments above)
I did change the web service so that it not double serialized.
I can now simplify the code to something like this:
private static JArray ConvertToJsonArray(string json)
{
var jsonObject = JObject.Parse(json);
return (JArray)jsonObject["d"];
}
And then convert it to my list of objects using:
private static IList<ThirdPartyClaim> ConvertJsonArrayToListOfClaims(JArray jsonArray)
{
return JsonConvert.DeserializeObject<List<ThirdPartyClaim>>(jsonArray.ToString());
}
Any other comments or improvements would be appreciated.

How do i convert a JSON string to a native C# array using a namespace compatible with Windows Store Apps?

I am trying to make a windows 8 Store app that gets results from a MySQL database from a PHP page as a REST service.
I'm looking for the PHP to return a JSON representation of an array of strings and have done that happily when dong the same between Javascript and PHP.
I need to take that same JSON string and use it in my C# Windows 8 store App, is there a way to take the return of that PHP page and convert it into a normal C# array, not a dictionary or more complex collection.
The database does have four fields so if i have to use a special object made for this i will, but I'd rather I didn't as this function doesn't require that amount of data.
The PHP page is like so - $search_text is passed in via a GET:
$databaseConnection = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if ($databaseConnection->connect_error)
{
echo "Database connection failed: $databaseConnection->connect_error";
}
else
{
$search_text = $search_text."%";
$query = "SELECT DISTINCT street FROM gritroutes WHERE street LIKE ? LIMIT 5";
$statement = $databaseConnection->prepare($query);
$statement->bind_param('s', $search_text);
$statement->execute();
$statement->store_result();
$statement->bind_result($street);
$autonumber = 1;
while ($statement->fetch())
{
$resultarr[] = $street;
}
$statement->close();
echo json_encode($resultarr);
}
Just to be clear. I am writing a Windows Store App, the System.Web Namespace is unavailable so i can't use JavaScriptSerializer.
Just to add to Matthew's answer, you can deserialize using Json.NET (you can get it from NuGet), you'd do something like:
List<string> myStrings = JsonConvert.DeserializeObject<List<string>>(myJson);
This is in:
using Newtonsoft.Json;
Check out this article for practical example.
EDIT
- I'd also like to throw in this link, since it's just awesome.
I hope this helps.
Take a look at the JavaScriptSerializer class.
string myJson = "{blablabla I'm json}";
var serializer = new JavaScriptSerializer();
var myStrings = serializer.Deserialize<List<string>>(myJson);
foreach (var str in myString)
{
Console.WriteLine(str);
}
You could also use native Windows.Data.Json classes to do the parsing:
string json = #"[""item1"", ""item2"", ""item3""]";
var array = JsonArray.Parse(json).Select(i => i.GetString()).ToArray();

Categories