Razor Umbraco 7 CurrentPage.GetPropertyValue Serialize issue - c#

i am using an for each but its not iterating properly instead its displaying a characters i think its Conversion issue can any one help me on this.
the array returing is CurrentPage.GetPropertyValue("promo")
[ { "alias": "1", "content": "1", "img": "/media/1069/509253678.jpg" }, { "alias": "Slide 2", "content": "2", "img": "/media/1074/636609180.jpg" } ]
the code is
#{
if (CurrentPage.HasValue("promo"))
{
var promoListValue = CurrentPage.GetPropertyValue("promo");
foreach (var item in promoListValue)
{
<span>#item </span>
}
}
}
but its displaying like this

You should implement a Property Value Converter for your custom datatype (now you are just getting the string out!)
so that from the json you saved in the node you can get the actual type.
See https://our.umbraco.org/documentation/extending/property-editors/value-converters

The issue you're seeing is because you are using the dynamic objects, which struggle to convert objects sometimes. It thinks the promo value field is a string, so your for-each loop is basically looping through each character of the string.
As Eyescream mentioned, you could write a property value converter to make your life much easier.

If the object is JSON, just derserialise it to a type and iterate over it.
http://www.newtonsoft.com/json/help/html/Overload_Newtonsoft_Json_JsonConvert_DeserializeObject.htm

Related

I need to access a JSON object inside another object or ArrayList via using dynamic. How can I access JSON objects using dynamic?

Here is my code.
dynamic obj = JsonConvert.DeserializeObject(response);
double value = obj.Price;
and here is my JSON data, I am trying grab the value that is inside Price. How would I access the value inside Price or even TotalPrice???
{
"Order": [
{
"Number": "1",
"Price": 1.99
}
],
"TotalPrice": 1.99
}
Please, any help is appreciated. Thank you.
You need to 'select' your object from array named Order (using index), then its property:
double value = obj.Order[0].Price;

How to pull a specific value from dynamic JSON dictionary in C#

I'm trying to pull one specific piece of data from the json received from a geocoding request.
This is not a duplicate of the myriads of similar-sounding questions, because the json is dynamic and has extremely irregular arrays that change slightly between responses, so I can't create a model to parse to, neither can I navigate through it using key names.
This is the json of one response:
{
"Response":{
"MetaInfo":{
"Timestamp":"2019-07-28T13:23:04.898+0000"
},
"View":[
{
"_type":"SearchResultsViewType",
"ViewId":0,
"Result":[
{
"Relevance":1.0,
"MatchLevel":"houseNumber",
"MatchQuality":{
"City":1.0,
"Street":[
0.9
],
"HouseNumber":1.0
},
"MatchType":"pointAddress",
"Location":{
"LocationId":"NT_Opil2LPZVRLZjlWNLJQuWB_0ITN",
"LocationType":"point",
"DisplayPosition":{
"Latitude":41.88432,
"Longitude":-87.63877
},
"NavigationPosition":[
{
"Latitude":41.88449,
"Longitude":-87.63877
}
],
"MapView":{
"TopLeft":{
"Latitude":41.8854442,
"Longitude":-87.64028
},
"BottomRight":{
"Latitude":41.8831958,
"Longitude":-87.63726
}
},
"Address":{
"Label":"425 W Randolph St, Chicago, IL 60606, United States",
"Country":"USA",
"State":"IL",
"County":"Cook",
"City":"Chicago",
"District":"West Loop",
"Street":"W Randolph St",
"HouseNumber":"425",
"PostalCode":"60606",
"AdditionalData":[
{
"value":"United States",
"key":"CountryName"
},
{
"value":"Illinois",
"key":"StateName"
},
{
"value":"Cook",
"key":"CountyName"
},
{
"value":"N",
"key":"PostalCodeType"
}
]
}
}
}
]
}
]
}
}
I'm trying to get just the two coordinates inside NavigationPosition.
Before I start the tedious work of creating a method to manually pull out the data I need from the unparsed string, does anyone have a solution? Is there a way to iterate anonymously through the json arrays using a foreach or if statement?
If the response is dynamic then one option is to use dynamic deserialization
var dynamicObject = JsonConvert.DeserializeObject<dynamic>(jsonAsString);
You can iterate this object and write defensive code by checking null.
I am assuming that "NavigationPosition" will always lie under "location" and in turn under a list of "Result" under list of "View"
something like this.. (symbolic code)
if(dynamicObject.View != null && dynamicObject.View[0] != null && dynamicObject.View[0].Result[0] != null && dynamicObject.View[0].Result[0].Location != null )
{
var navigationPosition = dynamicObject.View[0].Result[0].Location.NavigationPosition;
// do something with it
}
It seems really cumbersome but if you have no control over json response, I think you should be able to get it right after some iterations :)

Deserializing Some Odd JSON using C#

I have a JSON document coming from a vendor that looks like this:
{
"content": [{
"name": "Windows 8.1 x64",
"id": "Windows81x64",
"components": {
"Windows81x64": {
"propertyGroups": ["VirtualWindows81x64"],
"dependsOn": [],
"data": {
"provisioning_workflow": {
"fixed": {
"id": "WIMImageWorkflow",
"label": "WIMImageWorkflow"
}
},
"memory": {
"default": 2048,
"min": 2048,
"max": 16384
}
}
}
}
}]
}
Most of this document is fairly easy to deserialize into an object using the typical DataContractSerializer, however, there are a couple of keys/values that I am not sure what the "best practice" might be.
If you look at the "components" key the first key after that one is titled "Windows81x64". This key can change from document to document and it can be any value. It almost should be a 'Name' property of the collection but I can't control that. Furthermore, inside the 'Windows81x64' key there is another property called 'data'. According to the vendor the value of data is 'anonymous.' So, basically it can be anything.
Any ideas on the best way to deserialize this into a custom object when it comes to those parts of the document? Thank you.
You can deserialize dynamic ones as Dictionary<string, object>
Or if you know the value's type you can use Dictionary<string, ValueType> where the key of the dictionary would be the name (in your case Windows81x64)

Json.Net Serialize Complex Object to Xml Attribute And Value

Let's say I have a Json object that looks like this:
{
"Phones": [
{
"Phone": {
"Value": 123,
"#Type": "Foo"
}
}
]
}
I want to call JsonConvert.DeserializeXmlNode() but would like the resulting XML to look like this:
<Phones>
<Phone Type="Foo">123</Phone>
</Phones>
Currently Value is being deserialized to an xml element as a child of Phone, but I want it to be the XML value of Phone. Is there a way to do this using Json.Net, like a special operator that tells it to deserialize it as such, without having to create a custom serializer? Any help is apppreciated.
I just figured it out. using
"Phone": {
"#Type": "Foo",
"#text": 123
}
gives me the expected result. #text tells it not to create a child element for that value.

Getting an array of objects fron JSON string with Json.net

I am using Json.net for a project I do in C#, and I got lost looking for how to parse my JSON string to Objects.
so in my program I have a class Person that has 3 properties -
string Name,
int ID,
List condition
every time the user adds a person, the program writes it to a file, it looks like this:
{
"Name": "fsdf",
"ID": 234234,
"Conditions": [
"2",
"4",
"6"
]
}
{
"Name": "David",
"ID": 5555555,
"Conditions": [
"2",
"4",
"6"
]
}
The function I use to add new objects to the file-
public void AddPerson(Person person)
{
string output = JsonConvert.SerializeObject(person, Formatting.Indented);
StreamWriter file = new StreamWriter(#"../Data/Persons.json",true);
file.WriteLine(output);
file.Close();
}
Now I have a ComboBox and I want to fill it with all the names from the JSON string. and also there is a TextBox where the user inputs the ID number, and I want it to auto complete the input with the IDs that are already existing in the JSON file.
I think a good way is to parse each JSON object in my file to a Person object (in Persons array), then using a foreach loop add all the IDs in to a list which I can access later, and add all the names to the ComboBox.
using Newtonsofts' Json.net -
how do I parse each object in the JSON string to a separate Person object in my program?
*I've been looking through the docs and I cant find a solution.. also tried google but found nothing that addresses my problem.
*I started coding again after a long time off, and I am a bit new to JSON so I am sorry if my question is super noob :D.

Categories