1. 程式人生 > >Json的float單精度浮點數型別支援Can't assign value '11.88' (type System.Double) to type System.Single

Json的float單精度浮點數型別支援Can't assign value '11.88' (type System.Double) to type System.Single

今天遇到個問題Can’t assign value ‘11.88’ (type System.Double) to type System.Single
litjson不支援單精度浮點數float

只用修改JsonMapper.cs指令碼就可以,一共修改兩處

1.在JsonMapper.cs腳本里面增加如下程式碼

            #region  litjson support float  modified by codingriver wangguoqing 2018-10-29
            base_exporters_table[typeof
(float)] = delegate (object obj, JsonWriter writer) { writer.Write((float)obj); }; #endregion

增加到如下位置:
在這裡插入圖片描述

2.在JsonMapper.cs腳本里面增加如下程式碼

            #region  litjson support float  modified by codingriver  2018-10-29
            importer =
delegate (object input) { return Convert.ToSingle((double)input); }; RegisterImporter(base_importers_table, typeof(double), typeof(float), importer); #endregion

增加後是這樣的
在這裡插入圖片描述

3.最後貼上修改後的JsonMapper.cs程式碼:

#region Header
/** * JsonMapper.cs * JSON to .Net object and object to JSON conversions. * * The authors disclaim copyright to this source code. For more details, see * the COPYING file included with this distribution. **/ #endregion using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Reflection; using ILRuntime.Runtime.Intepreter; using ILRuntime.Runtime.Stack; using ILRuntime.CLR.Method; using ILRuntime.CLR.Utils; namespace LitJson { internal struct PropertyMetadata { public MemberInfo Info; public bool IsField; public Type Type; } internal struct ArrayMetadata { private Type element_type; private bool is_array; private bool is_list; public Type ElementType { get { if (element_type == null) return typeof (JsonData); return element_type; } set { element_type = value; } } public bool IsArray { get { return is_array; } set { is_array = value; } } public bool IsList { get { return is_list; } set { is_list = value; } } } internal struct ObjectMetadata { private Type element_type; private bool is_dictionary; private IDictionary<string, PropertyMetadata> properties; public Type ElementType { get { if (element_type == null) return typeof (JsonData); return element_type; } set { element_type = value; } } public bool IsDictionary { get { return is_dictionary; } set { is_dictionary = value; } } public IDictionary<string, PropertyMetadata> Properties { get { return properties; } set { properties = value; } } } internal delegate void ExporterFunc (object obj, JsonWriter writer); public delegate void ExporterFunc<T> (T obj, JsonWriter writer); internal delegate object ImporterFunc (object input); public delegate TValue ImporterFunc<TJson, TValue> (TJson input); public delegate IJsonWrapper WrapperFactory (); public class JsonMapper { #region Fields private static int max_nesting_depth; private static IFormatProvider datetime_format; private static IDictionary<Type, ExporterFunc> base_exporters_table; private static IDictionary<Type, ExporterFunc> custom_exporters_table; private static IDictionary<Type, IDictionary<Type, ImporterFunc>> base_importers_table; private static IDictionary<Type, IDictionary<Type, ImporterFunc>> custom_importers_table; private static IDictionary<Type, ArrayMetadata> array_metadata; private static readonly object array_metadata_lock = new Object (); private static IDictionary<Type, IDictionary<Type, MethodInfo>> conv_ops; private static readonly object conv_ops_lock = new Object (); private static IDictionary<Type, ObjectMetadata> object_metadata; private static readonly object object_metadata_lock = new Object (); private static IDictionary<Type, IList<PropertyMetadata>> type_properties; private static readonly object type_properties_lock = new Object (); private static JsonWriter static_writer; private static readonly object static_writer_lock = new Object (); #endregion #region Constructors static JsonMapper () { max_nesting_depth = 100; array_metadata = new Dictionary<Type, ArrayMetadata> (); conv_ops = new Dictionary<Type, IDictionary<Type, MethodInfo>> (); object_metadata = new Dictionary<Type, ObjectMetadata> (); type_properties = new Dictionary<Type, IList<PropertyMetadata>> (); static_writer = new JsonWriter (); datetime_format = DateTimeFormatInfo.InvariantInfo; base_exporters_table = new Dictionary<Type, ExporterFunc> (); custom_exporters_table = new Dictionary<Type, ExporterFunc> (); base_importers_table = new Dictionary<Type, IDictionary<Type, ImporterFunc>> (); custom_importers_table = new Dictionary<Type, IDictionary<Type, ImporterFunc>> (); RegisterBaseExporters (); RegisterBaseImporters (); } #endregion #region Private Methods private static void AddArrayMetadata (Type type) { if (array_metadata.ContainsKey (type)) return; ArrayMetadata data = new ArrayMetadata (); data.IsArray = type.IsArray; if (type.GetInterface ("System.Collections.IList") != null) data.IsList = true; if (type is ILRuntime.Reflection.ILRuntimeWrapperType) { var wt = (ILRuntime.Reflection.ILRuntimeWrapperType)type; if (data.IsArray) { data.ElementType = wt.CLRType.ElementType.ReflectionType; } else { data.ElementType = wt.CLRType.GenericArguments[0].Value.ReflectionType; } } else { foreach (PropertyInfo p_info in type.GetProperties()) { if (p_info.Name != "Item") continue; ParameterInfo[] parameters = p_info.GetIndexParameters(); if (parameters.Length != 1) continue; if (parameters[0].ParameterType == typeof(int)) data.ElementType = p_info.PropertyType; } } lock (array_metadata_lock) { try { array_metadata.Add (type, data); } catch (ArgumentException) { return; } } } private static void AddObjectMetadata (Type type) { if (object_metadata.ContainsKey (type)) return; ObjectMetadata data = new ObjectMetadata (); if (type.GetInterface ("System.Collections.IDictionary") != null) data.IsDictionary = true; data.Properties = new Dictionary<string, PropertyMetadata> (); foreach (PropertyInfo p_info in type.GetProperties ()) { if (p_info.Name == "Item") { ParameterInfo[] parameters = p_info.GetIndexParameters (); if (parameters.Length != 1) continue; if (parameters[0].ParameterType == typeof(string)) { if (type is ILRuntime.Reflection.ILRuntimeWrapperType) { data.ElementType = ((ILRuntime.Reflection.ILRuntimeWrapperType)type).CLRType.GenericArguments[1].Value.ReflectionType; } else data.ElementType = p_info.PropertyType; } continue; } PropertyMetadata p_data = new PropertyMetadata (); p_data.Info = p_info; p_data.Type = p_info.PropertyType; data.Properties.Add (p_info.Name, p_data); } foreach (FieldInfo f_info in type.GetFields ()) { PropertyMetadata p_data = new PropertyMetadata (); p_data.Info = f_info; p_data.IsField = true; p_data.Type = f_info.FieldType; data.Properties.Add (f_info.Name, p_data); } lock (object_metadata_lock) { try { object_metadata.Add (type, data); } catch (ArgumentException) { return; } } } private static void AddTypeProperties (Type type) { if (type_properties.ContainsKey (type)) return; IList<PropertyMetadata> props = new List<PropertyMetadata> (); foreach (PropertyInfo p_info in type.GetProperties ()) { if (p_info.Name == "Item") continue; PropertyMetadata p_data = new PropertyMetadata (); p_data.Info = p_info; p_data.IsField = false; props.Add (p_data); } foreach (FieldInfo f_info in type.GetFields ()) { PropertyMetadata p_data = new PropertyMetadata (); p_data.Info = f_info; p_data.IsField = true; props.Add (p_data); } lock (type_properties_lock) { try { type_properties.Add (type, props); } catch (ArgumentException) { return; } } } private static MethodInfo GetConvOp (Type t1, Type t2) { lock (conv_ops_lock) { if (! conv_ops.ContainsKey (t1)) conv_ops.Add (t1, new Dictionary<Type, MethodInfo> ()); } if (conv_ops[t1].ContainsKey (t2)) return conv_ops[t1][t2]; MethodInfo op = t1.GetMethod ( "op_Implicit", new Type[] { t2 }); lock (conv_ops_lock) { try { conv_ops[t1].Add (t2, op); } catch (ArgumentException) { return conv_ops[t1][t2]; } } return op; } private static object ReadValue (Type inst_type, JsonReader reader) { reader.Read (); if (reader.Token == JsonToken.ArrayEnd) return null; //ILRuntime doesn't support nullable valuetype Type underlying_type = inst_type;//Nullable.GetUnderlyingType(inst_type); Type value_type = inst_type; if (reader.Token == JsonToken.Null) { if (inst_type.IsClass || underlying_type != null) { return null; } throw new JsonException (String.Format ( "Can't assign null to an instance of type {0}", inst_type)); } if (reader.Token == JsonToken.Double || reader.Token == JsonToken.Int || reader.Token == JsonToken.Long || reader.Token == JsonToken.String || reader.Token == JsonToken.Boolean) { Type json_type = reader.Value.GetType(); var vt = value_type is ILRuntime.Reflection.ILRuntimeWrapperType ? ((ILRuntime.Reflection.ILRuntimeWrapperType)value_type).CLRType.TypeForCLR : value_type; if (vt.IsAssignableFrom(json_type)) return reader.Value; if (vt is ILRuntime.Reflection.ILRuntimeType && ((ILRuntime.Reflection.ILRuntimeType)vt).ILType.IsEnum) { if (json_type == typeof(int) || json_type == typeof(long) || json_type == typeof(short) || json_type == typeof(byte)) return reader.Value; } // If there's a custom importer that fits, use it if (custom_importers_table.ContainsKey (json_type) && custom_importers_table[json_type].ContainsKey ( vt)) { ImporterFunc importer = custom_importers_table[json_type][vt]; return importer (reader.Value); } // Maybe there's a base importer that works if (base_importers_table.ContainsKey (json_type) && base_importers_table[json_type].ContainsKey ( vt)) { ImporterFunc importer = base_importers_table[json_type][vt];

相關推薦

Json的float單精度點數型別支援Can&#39;t assign value &#39;11.88&#39; (type System.Double) to type System.Single

今天遇到個問題Can’t assign value ‘11.88’ (type System.Double) to type System.Single litjson不支援單精度浮點數float 只用修改JsonMapper.cs指令碼就可以,一共修改兩處 1.在Js

單精度點數(float)加法計算出錯

它的 位數 nbsp 有效 丟失 com image 替換 原因 場景:   一個float型的變量賦值1170601,加上19000000,結果出現錯誤。 原因:   float占用4個字節(32位)存儲空間,包括符號位1位,階碼位8位,尾數23位。浮點數精度與

單精度點數(float)與雙精度點數double)的區別:

1、單精度,也就是 float ,在 32 位機器上用 4 個位元組來儲存的;而雙精度double是用 8 個位元組來儲存的,這是他們最本質的區別。  2、由於儲存位不同,8位,16位他們能表示的數值的範圍就不同,也就是能準確表示的數的位數就不同。 單精度浮點的表示範圍:-3.40E+38

dev編譯器:c++如何讓其輸出小數16.84,點數型別資料!

devc++,也不知道是我不會用,還是他的BUG~ 竟然不可以輸出浮點數! 想要輸出浮點數,不可以直接用C++裡的 cout<<a<<""; 需要改用: printf(""); 程式碼: #include<iostream> using namespace st

單精度點數操作

加法 precision n) ack mil ring oid www creat 用數組存儲32位單精度浮點數,並且實現有效位右移,有效數加法等,可用於計算機浮點加減法的底層模擬。 1 package com.computerOrganizationAndArch

tensorflow-檢測點數型別check_numerics

引數 'tensor' 要屬於以下型別才能通過 bfloat16, float16, float32, float64,返回原tensorflow。否則報InvalidArgument 錯誤。 #!/usr/bin/env python2 # -*- coding: utf-8 -*-

CS:APP3e Homework 2.97 關於整型轉單精度點數的方法討論

CS:APP3e Homework 2.97 關於整型轉單精度浮點數的方法討論 關於整型轉單精度浮點數的方法討論 CS:APP原題 題目分析 實現程式碼 原理解釋 其他方法 啟示與思考 關

單精度點數的二進位制表示中,為什麼指數的表示要與127相加作為結果?

我們知道:  舉個例子: 上面的例子中,我們知道E代表的是冪的大小,而存入計算機的e則為E+127,那麼問題來了,這裡為什麼要加上127這個數呢? 答案: 其實,也就是說:計算機表示單精度浮點數時,是用8位去儲存指數部分,在數值上面,表示0~255,但

使用 C++ bitset 操縱點數型別(float、double

#include <bitset> bitset 類是將資料轉換為二進位制位(遵循 IEEE 754 的儲存和表示方法,關於 IEEE 754 更多更全的使用方法和原理請見 IEEE 754——計算機中浮點數的表示方法 )。 如下: #in

單精度點數的取值,表示以及相關

取值範圍及精度 可以表示的範圍為±3.40282 * 10^38(1.1111…1×2^127)即: 0-11111110-11111111111111111111111(23個1) 單精度浮點數可以表示1.175 * 10-38(1.00…0×2^-

Hibernate 將點數型別設定為 BigDecimal,保證計算的精確性

浮點計算精度損失的文章比較多,我就不多說了,搜了一篇,見參考1。 設定方式如下: 大數字有精度precision和小數位scale兩個引數可設定,精度的位數是包含小數位數的,即整數位=精度-小數位。對於超過小數位的小數,用四捨五入法進行擷取。 運算過程中保留6位小數,儲存到

實數與單精度點數的轉換

單精度浮點數的表示方法 三個主要成分是: Sign(1bit):表示浮點數是正數還是負數。0表示正數,1表示負數 Exponent(8bits):指

使用Java進行udp-demo程式設計時碰到的consumer和producter無法連線並報出“java.net.SocketException: Can&#39;t assign requested address”問題

在用Java編寫了一個udp生產者和消費者的demo時,在生產者啟動的時候會丟擲異常 java.net.SocketException: Can't assign requested address at java.net.PlainDatagramSocketImpl.join(Native

使用Java進行udp-demo編程時碰到的consumer和producter無法連接並報出“java.net.SocketException: Can&#39;t assign requested address”問題

ons col 添加 使用 native 啟動參數 tag res strac 在用Java編寫了一個udp生產者和消費者的demo時,在生產者啟動的時候會拋出異常 java.net.SocketException: Can‘t assign requested addr

解決Can&#39;t map file, errno=22 file &#39;xxx&#39; for architecture arm64(armv7)問題!

今天在引入一個靜態framework庫時候,編譯遇到了“Can't map file, errno=22 file 'xxx' for architecture arm64(armv7)”問題! 起因是我在主專案中,build setting-----》other linker flags

使用Ehcache緩存同步啟動時拋出異常net.sf.ehcache.CacheException: Can&#39;t assign requested address

request ESS 端口 true 內網 ear .net 了無 ehcache 這個問題在插入公司內網網線的時候不會復現,由於我使用的是公司無線網絡,故導致此問題。 具體解決辦法是:在啟動服務時,指定使用默認ipv4的網絡接口。可以在啟動jvm時添加參數-Djava

The file * couldn&#39;t be opened because you don&#39;t have permission to view it

images logs building mis 人的 iss perm 也有 編譯 The file * couldn‘t be opened because you don‘t have permission to view it. 最近,經常在接收別人的代碼時出現,

java.sql.SQLException: Column count doesn&#39;t match value count at row 1

acc host quest pac cti class inter LV orm 1、異常提示:Cause: java.sql.SQLException: Column count doesn‘t match value count at row 1 ; bad SQL

MySql數據庫執行insert時候報錯:Column count doesn&#39;t match value count at row 1

doesn 發現 相同 ins bsp cti sql數據庫 當前 val 遇到這個問題之後,第一反應就是前後列數不等造成的,但是我檢查SQL之後,發現列數是相同得,但是插入還是有問題,然後又寫了簡單得SQL只插入不為空得字段,執行還是報這個錯,最後請教了高人,指點之後,大

Column count doesn&#39;t match value count at row 1(Python操作MySQL資料庫時的報錯)

首先,這個錯誤的意思是,我們插入資料庫的列與資料庫中的列不是一一對應的。 當使用Python操作MySQL資料庫時,如果id是自增,或者timestamp是自動生成的時候,我們不能採用 "INSERT INTO 表名 VALUES (%s, %s, %s, %s, %s, %s,