logo
Tags down

shadow

Converting JSON String to Dictionary<String, Any> serializes Boolean as Int


By : Mariyah
Date : October 17 2020, 06:10 AM
To fix this issue This is just a debugger description of the result.
For Bool it uses NSNumber with values 1 as true and 0 as false.
code :
guard let json = self.inputArgumentsString?.toJson,
        let boolean = json["BoolArgument"] as? Bool
        else { return }

print(boolean)
for key, value in json {
  if let number = value as? NSNumber {
    let numberType = CFNumberGetType(number as CFNumberRef)

    switch numberType {
      case .charType:
        //Bool
        print(key, value as? Bool)
      case .sInt8Type, .sInt16Type, .sInt32Type, .sInt64Type, .shortType, .intType, .longType, .longLongType, .cfIndexType, .nsIntegerType:
        //Int
        print(key, value as? Int)
      case .float32Type, .float64Type, .floatType, .doubleType, .cgFloatType:
        //Double
        print(key, value as? Double)
    }
  }
}


Share : facebook icon twitter icon

converting dictionary string string to json string


By : Kilroy Max
Date : March 29 2020, 07:55 AM
may help you . How can i convert my dictionary , Try this using extension methods.
code :
public static class Extensions
{
    public static string FromDictionaryToJson(this Dictionary<string, string> dictionary)
    {
        var kvs = dictionary.Select(kvp => string.Format("\"{0}\":\"{1}\"", kvp.Key, string.Concat(",", kvp.Value)));
        return string.Concat("{", string.Join(",", kvs), "}");
    }

    public static Dictionary<string, string> FromJsonToDictionary(this string json)
    {
        string[] keyValueArray = json.Replace("{", string.Empty).Replace("}", string.Empty).Replace("\"", string.Empty).Split(',');
        return keyValueArray.ToDictionary(item => item.Split(':')[0], item => item.Split(':')[1]);
    }
}
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, string> dictss = new Dictionary<string, string>();

            dictss.Add("onekey", "oneval");
            dictss.Add("twokey", "twoval");
            dictss.Add("threekey", "threeval");
            dictss.Add("fourkey", "fourval");
            dictss.Add("fivekey", "fiveval");

            string jsonString = dictss.FromDictionaryToJson(); //call extension method

            Console.WriteLine(jsonString);

            Dictionary<string, string> dictss2 = jsonString.FromJsonToDictionary(); //call extension method

            foreach(KeyValuePair<string,string> kv in dictss2)
                Console.WriteLine(string.Format("key={0},value={1}", kv.Key, kv.Value));
        }
    }
        public string FromDictionaryToJson(Dictionary<string, string> dictionary)
        {
            var kvs = dictionary.Select(kvp => string.Format("\"{0}\":\"{1}\"", kvp.Key, string.Join(",", kvp.Value)));
            return string.Concat("{", string.Join(",", kvs), "}");
        }

        public Dictionary<string, string> FromJsonToDictionary(string json)
        {
            string[] keyValueArray = json.Replace("{", string.Empty).Replace("}", string.Empty).Replace("\"", string.Empty).Split(',');
            return keyValueArray.ToDictionary(item => item.Split(':')[0], item => item.Split(':')[1]);
        }

Json.NET serializes enum as string even with default settings


By : ChrisTSG
Date : March 29 2020, 07:55 AM
To fix this issue This is happening because JsonConvert.SerializeObject applies the incoming settings on top of the default settings, by internally calling JsonSerializer.CreateDefault(JsonSerializerSettings settings). I don't know if/where this behavior is documented, but it's visible in the source code. Thus the default list of converters will be used in addition to the empty list of locally specified converters, meaning the default StringEnumConverter will get used.
You have a couple options to work around this:
code :
public static class JsonExtensions
{
    public static string SerializeObjectNoDefaultSettings(object value, Formatting formatting, JsonSerializerSettings settings)
    {
        var jsonSerializer = JsonSerializer.Create(settings);
        jsonSerializer.Formatting = formatting;

        StringBuilder sb = new StringBuilder(256);
        StringWriter sw = new StringWriter(sb, CultureInfo.InvariantCulture);
        using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
        {
            jsonWriter.Formatting = jsonSerializer.Formatting;
            jsonSerializer.Serialize(jsonWriter, value);
        }

        return sw.ToString(); 
    }
}
var json = JsonExtensions.SerializeObjectNoDefaultSettings(value, Formatting.None, new JsonSerializerSettings());
public class IntegerEnumConverter : StringEnumConverter
{
    public override bool CanRead { get { return false; } }

    public override bool CanWrite { get { return false; } }
}
var json = JsonConvert.SerializeObject(value, Formatting.None, new JsonSerializerSettings { Converters = new JsonConverter[] { new IntegerEnumConverter() } });

Converting boolean to int in json string


By : Carl Stanley Hopkins
Date : March 29 2020, 07:55 AM
help you fix your problem If you are willing to switch to , you can use the solution from Convert an int to bool with Json.Net.
If you wish to continue using JavaScriptSerializer, you will need to create a JavaScriptConverter for your MyObject type as follows:
code :
class MyObjectConverter : JavaScriptConverter
{
    public override IEnumerable<Type> SupportedTypes
    {
        get { return new[] { typeof(MyObject) }; }
    }

    // Custom conversion code below

    const string myPropName = "MyProp";

    public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
    {
        object value;
        if (dictionary.TryGetValue(myPropName, out value))
        {
            dictionary[myPropName] = !value.IsNullOrDefault();
        }

        var myObj = new JavaScriptSerializer().ConvertToType<MyObject>(dictionary);
        return myObj;
    }

    public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
    {
        var myObj = (MyObject)obj;

        // Generate a default serialization.  Is there an easier way to do this?
        var defaultSerializer = new JavaScriptSerializer();
        var dict = defaultSerializer.Deserialize<Dictionary<string, object>>(defaultSerializer.Serialize(obj));

        dict[myPropName] = myObj.MyProp ? 1 : 0;

        return dict;
    }
}

public static class ObjectExtensions
{
    public static bool IsNullOrDefault(this object value)
    {
        // Adapted from https://stackoverflow.com/questions/6553183/check-to-see-if-a-given-object-reference-or-value-type-is-equal-to-its-default
        if (value == null)
            return true;
        Type type = value.GetType();
        if (!type.IsValueType)
            return false; // can't be, as would be null
        if (Nullable.GetUnderlyingType(type) != null)
            return false; // ditto, Nullable<T>
        object defaultValue = Activator.CreateInstance(type); // must exist for structs
        return value.Equals(defaultValue);
    }
}
        var serializer = new JavaScriptSerializer();
        serializer.RegisterConverters(new JavaScriptConverter[] { new MyObjectConverter() } );

        var json = serializer.Serialize(myObject);
public class MyObject
{
    public bool MyProp { get; set; }

    public string SomeOtherProperty { get; set; }
}

JSONField serializes as json for POST, but string for GET


By : Vtollar
Date : March 29 2020, 07:55 AM
will be helpful for those in need You can override the to_internal_value and to_representation in a new serializer field to handle the return data for JSON field.
code :
class JSONSerializerField(serializers.Field):
    """Serializer for JSONField -- required to make field writable"""

    def to_internal_value(self, data):
        return data

    def to_representation(self, value):
        return value
class SomeSerializer(serializers.ModelSerializer):
    json_field = JSONSerializerField()

    class Meta:
        model = SomeModelClass
        fields = ('json_field', )

servicestack serializes to empty json string


By : harishkumar manda
Date : March 29 2020, 07:55 AM
seems to work fine I am having a strange issue with ServiceStack (SS). The entity I pass to the method is always serialized to empty json string by SS. So s is always "{}". I debug and see that the entity is a hydrated instance with properties with values. , ServiceStack serializes only serializes public properties.
Related Posts Related Posts :
  • How to create UIButton Pulse animation using Swift?
  • using swift can we airplay photos on Apple TV programmatically?
  • Where to find the shared secret for iOS App Store receipt validation?
  • AVRoutePickerView Won't Change Color when Airplay is Active
  • What sections of Apple Health app are available via the x-apple-health:// URL scheme?
  • Flutter error on pod install: CocoaPods could not find compatible versions for pod "Firebase/CoreOnly"
  • RegEx for matching specific URLs with lowercase and dashes
  • How to build and use C library in iOS project?
  • UICollectionView cell spacing for both portrait and landscape
  • How to capture cell data from UITableView with multiple cell prototypes?
  • Swift run multiple block of codes asynchronously in background thread in order
  • how do I trigger the click event on AVRoutePickerView using swift
  • Animate UIImageView start from rounded topRight corner and end with Rectangle
  • Xamarin.iOS binding for a swift library
  • How to keep tableFooterView always on bottom of UITableView
  • Why not getting response from one URL?
  • Why might my iOS app be stuck on splash screen for Apple reviewers but not for me?
  • Installing .ipa over the air does not open
  • How to Add Business Logic in CollectionView?
  • is there a shortcut to know, when I'm running my app, which view controller am I in?
  • error: Unable to load contents of file list: '/Target Support Files/Pods-xx/Pods-xx-frameworks-Debug-input-files.xcfilel
  • Encode and Decode a Class in ios
  • How to get device token using firebase?
  • Removing duplicate objects from fetch based on object parameter UPDATED Swift
  • Class variable assignment is not working inside a Alamofire request block
  • Is it possible to do Augmented Faces on iOS with ARCore?
  • How to differentiate between event saved through my app and event saved by using calendar app using EventKit?
  • Pushing Firebase events To a Table View
  • What happens to local files on iOS when the app is updated?
  • How to make a variable accessible from a different swift file?
  • I want to generate QR Code encrypted in such a way that it is only read by own QRScanner app
  • Update Phone Number in Firebase Authentication - Swift
  • Convert bits per second (bps) to a human readable size format
  • How to not invalidate observer when binding is disposed in RxSwift?
  • What happen if I return false in didFinishLaunchingWithOptions?
  • How to detect hand palm and its orientation (like facing outwards)?
  • New OutputDeviceUID is nil msg when instantiating MPVolumeView
  • How to add sound feedback like pickerview in collectionview?
  • Cannot assign value of type '[String]' to type 'String?'
  • How do I make an iOS app support iPhone 6, without supporting iPhone 5S?
  • iOS app -- no cellular access to our domain on some devices
  • How to show image from url in ios swift
  • Importing image from photo library into an app in xcode
  • Delegate won't work using three view controllers
  • Why can such code be compiled? Call popToRootViewControllerAnimated in iOS UIViewController?
  • Open native UIViewController in Flutter
  • How to place 3D object (.scn file) on detected vertical plane which should be parallel to plane in ARKIt?
  • Delegate data from one UIViewController to another one
  • WARNING: The advertisement key 'Service Data' is not allowed
  • How do I check if a particular app is installed on the user's device on iOS?
  • How to check if user has paid for an Auto Renewal Subscription In App Purchase in Swift
  • Dynamic-height UICollectionView inside a dynamic-height UITableViewCell
  • This iPhone 7 (Model 1660, 1778, 1779, 1780) is running iOS 12.3.1 (16F203), which may not be supported by this version
  • How to fix issue: no rule to process file /FBSDKCoreKit.modulemap' of type 'sourcecode.module-map' for architecture x86_
  • Apple iOS Inapp purchase Server to Server Notifications' 'Cancel' notification cases?
  • Cannot assign to property 'observationTime' is a get-only property
  • How do I use Codable to decode json response which has changing keys?
  • Saving an array in Swift
  • Swift pushViewController Works on iPad but not iPhone
  • Parsing JSON response into a struct
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk