json 常用的序列化 反序列化對象 代碼


序列化對象:

----------------------------------------------------------

Person p = new Person()
{
Name = "Hexiang",
Birthday = DateTime.Parse("2017-02-20 14:30:00"),
Gender = "男",
Love = "Ball"
};
string strJson = JsonConvert.SerializeObject(p, Formatting.Indented);

------------------------------------------------------

序列化字典

Dictionary<string, int> dicPoints = new Dictionary<string, int>(){
{ "James", 9001 },
{ "Jo", 3474 },
{ "Jess", 11926 }
};

string strJson = JsonConvert.SerializeObject(dicPoints, Formatting.Indented);

------------------------------------

序列化list

List<string> lstGames = new List<string>()
{
"Starcraft",
"Halo",
"Legend of Zelda"
};

string strJson = JsonConvert.SerializeObject(lstGames);

-----------------------------------

序列化到json文件中

Person p = new Person()
{
Name = "Hexiang",
Birthday = DateTime.Parse("2017-02-20 14:30:00"),
Gender = "男",
Love = "Ball"
};
using (StreamWriter file = File.CreateText(@"d:\person.json"))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(file, p);
}

--------------------------------

序列化 枚舉

List<StringComparison> stringComparisons = new List<StringComparison>
{
StringComparison.CurrentCulture,
StringComparison.Ordinal
};

string jsonWithoutConverter = JsonConvert.SerializeObject(stringComparisons);

this.txtJson.Text = jsonWithoutConverter;//序列化出來是枚舉所代表的整數值


string jsonWithConverter = JsonConvert.SerializeObject(stringComparisons, new StringEnumConverter());
this.txtJson.Text += "\r\n";
this.txtJson.Text += jsonWithConverter;//序列化出來是枚舉所代表的文本值
// ["CurrentCulture","Ordinal"]

List<StringComparison> newStringComparsions = JsonConvert.DeserializeObject<List<StringComparison>>(
jsonWithConverter,
new StringEnumConverter());

-------------------------------------

序列化dataset

string json = JsonConvert.SerializeObject(dataSet, Formatting.Indented);

-------------------------------

序列化jrow

JavaScriptSettings settings = new JavaScriptSettings
{
OnLoadFunction = new JRaw("OnLoad"),
OnUnloadFunction = new JRaw("function(e) { alert(e); }")
};

string json = JsonConvert.SerializeObject(settings, Formatting.Indented);

-----------------------

反序列化list

string json = @"['Starcraft','Halo','Legend of Zelda']";
List<string> videogames = JsonConvert.DeserializeObject<List<string>>(json);
this.txtJson.Text = string.Join(", ", videogames.ToArray());

---------------------------------

反序列化字典

string json = @"{
'href': '/account/login.aspx',
'target': '_blank'
}";

Dictionary<string, string> dicAttributes = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);

this.txtJson.Text = dicAttributes["href"];
this.txtJson.Text += "\r\n";
this.txtJson.Text += dicAttributes["target"];

--------------------------------

反序列化匿名類

var definition = new { Name = "" };

string json1 = @"{'Name':'James'}";
var customer1 = JsonConvert.DeserializeAnonymousType(json1, definition);
this.txtJson.Text = customer1.Name;
this.txtJson.Text += "\r\n";

string json2 = @"{'Name':'Mike'}";
var customer2 = JsonConvert.DeserializeAnonymousType(json2, definition);
this.txtJson.Text += customer2.Name;

--------------------------------------------

反序列化dataset

string json = @"{
'Table1': [
{
'id': 0,
'item': 'item 0'
},
{
'id': 1,
'item': 'item 1'
}
]
}";

DataSet dataSet = JsonConvert.DeserializeObject<DataSet>(json);

-----------------------------------------

從文件中反序列化對象

using (StreamReader file = File.OpenText(@"d:\person.json"))
{
JsonSerializer serializer = new JsonSerializer();
Person p = (Person)serializer.Deserialize(file, typeof(Person));
this.txtJson.Text = p.Name;
}

----------------------------------------------------

反序列化有構造函數的對象

string json = @"{'Url':'http://www.google.com'}";

//直接序列化會報錯,需要設置JsonSerializerSettings中ConstructorHandling才可以。
Website website = JsonConvert.DeserializeObject<Website>(json, new JsonSerializerSettings
{
ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor
});

this.txtJson.Text = website.Url;

------------------------------------------

反序列化對象,如果有構造函數中,創建對象,則用Json的進行替換

//
string json = @"{
'Name': 'James',
'Offices': [
'Auckland',
'Wellington',
'Christchurch'
]
}";

UserViewModel model1 = JsonConvert.DeserializeObject<UserViewModel>(json);

this.txtJson.Text = string.Join(",", model1.Offices);//默認會重復
this.txtJson.Text += "\r\n";

//每次從Json中創建新的對象
UserViewModel model2 = JsonConvert.DeserializeObject<UserViewModel>(json, new JsonSerializerSettings
{
ObjectCreationHandling = ObjectCreationHandling.Replace
});

this.txtJson.Text = string.Join(",", model2.Offices);

--------------------------------------

序列化對象的時候去掉沒有賦值 的屬性

Person person = new Person();

string jsonIncludeDefaultValues = JsonConvert.SerializeObject(person, Formatting.Indented);

this.txtJson.Text=(jsonIncludeDefaultValues);//默認的序列化,帶不賦值的屬性

this.txtJson.Text += "\r\n";

string jsonIgnoreDefaultValues = JsonConvert.SerializeObject(person, Formatting.Indented, new JsonSerializerSettings
{
DefaultValueHandling = DefaultValueHandling.Ignore //去掉不賦值的屬性
});

this.txtJson.Text+=(jsonIgnoreDefaultValues);

-----------------------------------------------------------------------

反序列化類中沒有對應對屬性 處理方法

string json = @"{
'FullName': 'Dan Deleted',
'Deleted': true,
'DeletedDate': '2013-01-20T00:00:00'
}";

try
{
JsonConvert.DeserializeObject<Account>(json, new JsonSerializerSettings
{
MissingMemberHandling = MissingMemberHandling.Error //要么忽略,要么報錯
});
}
catch (JsonSerializationException ex)
{
this.txtJson.Text=(ex.Message);
// Could not find member 'DeletedDate' on object of type 'Account'. Path 'DeletedDate', line 4, position 23.
}

---------------------------------------------------------

去掉null值的序列化對象

Person person = new Person
{
Name = "Nigal Newborn"
};

//默認的序列化
string jsonIncludeNullValues = JsonConvert.SerializeObject(person, Formatting.Indented);

this.txtJson.Text=(jsonIncludeNullValues);
this.txtJson.Text += "\r\n";

//去掉Null值的序列化
string jsonIgnoreNullValues = JsonConvert.SerializeObject(person, Formatting.Indented, new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore //可以忽略,可以包含
});

this.txtJson.Text+=(jsonIgnoreNullValues);

-----------------------------

序列化的時候日期的格式化

DateTime mayanEndOfTheWorld = new DateTime(2012, 12, 21);

string jsonIsoDate = JsonConvert.SerializeObject(mayanEndOfTheWorld);

this.txtJson.Text = (jsonIsoDate);

this.txtJson.Text += "\r\n";
string jsonMsDate = JsonConvert.SerializeObject(mayanEndOfTheWorld, new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
});

this.txtJson.Text += (jsonMsDate);
// "\/Date(1356044400000+0100)\/"
this.txtJson.Text += "\r\n";
string json = JsonConvert.SerializeObject(mayanEndOfTheWorld, new JsonSerializerSettings
{
DateFormatString = "yyyy-MM-dd",
Formatting = Formatting.Indented
});
this.txtJson.Text += json;

----------------------------

序列化設置時區

 

Flight flight = new Flight
{
Destination = "Dubai",
DepartureDate = new DateTime(2013, 1, 21, 0, 0, 0, DateTimeKind.Unspecified),
DepartureDateUtc = new DateTime(2013, 1, 21, 0, 0, 0, DateTimeKind.Utc),
DepartureDateLocal = new DateTime(2013, 1, 21, 0, 0, 0, DateTimeKind.Local),
Duration = TimeSpan.FromHours(5.5)
};

string jsonWithRoundtripTimeZone = JsonConvert.SerializeObject(flight, Formatting.Indented, new JsonSerializerSettings
{
DateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind
});

this.txtJson.Text=(jsonWithRoundtripTimeZone);
this.txtJson.Text += "\r\n";
string jsonWithLocalTimeZone = JsonConvert.SerializeObject(flight, Formatting.Indented, new JsonSerializerSettings
{
DateTimeZoneHandling = DateTimeZoneHandling.Local
});

this.txtJson.Text+=(jsonWithLocalTimeZone);
this.txtJson.Text += "\r\n";

string jsonWithUtcTimeZone = JsonConvert.SerializeObject(flight, Formatting.Indented, new JsonSerializerSettings
{
DateTimeZoneHandling = DateTimeZoneHandling.Utc
});

this.txtJson.Text += (jsonWithUtcTimeZone);
this.txtJson.Text += "\r\n";

string jsonWithUnspecifiedTimeZone = JsonConvert.SerializeObject(flight, Formatting.Indented, new JsonSerializerSettings
{
DateTimeZoneHandling = DateTimeZoneHandling.Unspecified
});

this.txtJson.Text += (jsonWithUnspecifiedTimeZone);

---------------------------------------

序列化默認設置

// settings will automatically be used by JsonConvert.SerializeObject/DeserializeObject
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
Formatting = Formatting.Indented,
ContractResolver = new CamelCasePropertyNamesContractResolver()
};

Person s = new Person()
{
Name = "Eric",
Birthday = new DateTime(1980, 4, 20, 0, 0, 0, DateTimeKind.Utc),
Gender = "男",
Love = "Web Dude"
};

string json = JsonConvert.SerializeObject(s);
this.txtJson.Text = json;

-----------------------------------------

序列化ImmutableList

//ImmutableList<string> l = ImmutableList.CreateRange(new List<string>
// {
// "One",
// "II",
// "3"
// });

//string json = JsonConvert.SerializeObject(l, Formatting.Indented);

-------------------------------------------------

----------------------------------------

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM