本文整理汇总了C#中JsonArray.Add方法的典型用法代码示例。如果您正苦于以下问题:C# JsonArray.Add方法的具体用法?C# JsonArray.Add怎么用?C# JsonArray.Add使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类JsonArray
的用法示例。
在下文中一共展示了JsonArray.Add方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ToJson
public static JsonObject ToJson(Dominion.GameDescription gameDescription, int starRating)
{
JsonObject root = new Windows.Data.Json.JsonObject();
root.Add(jsonNameDeck, ToJson(gameDescription));
JsonArray expansionArray = new JsonArray();
Dominion.Expansion[] presentExpansions;
Dominion.Expansion[] missingExpansions;
gameDescription.GetRequiredExpansions(out presentExpansions, out missingExpansions);
foreach (var expansion in presentExpansions)
{
JsonObject expansionObject = new JsonObject();
expansionObject.Add("name", JsonValue.CreateStringValue(expansion.ToProgramaticName()));
expansionObject.Add("present", JsonValue.CreateBooleanValue(true));
expansionArray.Add(expansionObject);
}
foreach (var expansion in missingExpansions)
{
JsonObject expansionObject = new JsonObject();
expansionObject.Add("name", JsonValue.CreateStringValue(expansion.ToProgramaticName()));
expansionObject.Add("present", JsonValue.CreateBooleanValue(false));
expansionArray.Add(expansionObject);
}
root.Add(jsonNameRequiredExpansions, expansionArray);
root.Add(jsonNameRating, JsonValue.CreateNumberValue(starRating));
return root;
}
示例2: Search
public async Task<string> Search(string search)
{
using (AutoResetEvent handle = new AutoResetEvent(false))
{
JsonObject message = new JsonObject();
message.Add("method", JsonValue.CreateStringValue("core.library.search"));
JsonObject queryObject = new JsonObject();
queryObject.Add("track_name", JsonValue.CreateStringValue(search));
JsonArray urisArray = new JsonArray();
urisArray.Add(JsonValue.CreateStringValue("spotify:"));
JsonObject paramsObject = new JsonObject();
paramsObject.Add("query", queryObject);
paramsObject.Add("uris", urisArray);
message.Add("params", paramsObject);
string result = null;
await Send(message, searchResult =>
{
JsonArray tracks = searchResult.GetNamedArray("result")[0].GetObject().GetNamedArray("tracks");
result = tracks.First().GetObject().GetNamedString("uri");
handle.Set();
});
handle.WaitOne(TimeSpan.FromSeconds(30));
return result;
}
}
示例3: Stringify
public string Stringify()
{
JsonArray jsonArray = new JsonArray();
foreach (School school in Education)
{
jsonArray.Add(school.ToJsonObject());
}
JsonObject jsonObject = new JsonObject();
jsonObject[idKey] = JsonValue.CreateStringValue(Id);
// Treating a blank string as null
if (String.IsNullOrEmpty(Phone))
{
jsonObject[phoneKey] = JsonValue.CreateNullValue();
}
else
{
jsonObject[phoneKey] = JsonValue.CreateStringValue(Phone);
}
jsonObject[nameKey] = JsonValue.CreateStringValue(Name);
jsonObject[educationKey] = jsonArray;
jsonObject[timezoneKey] = JsonValue.CreateNumberValue(Timezone);
jsonObject[verifiedKey] = JsonValue.CreateBooleanValue(Verified);
return jsonObject.Stringify();
}
示例4: CreateJsonTest
private void CreateJsonTest()
{
JsonArray weekDiet = new JsonArray();
for(int i=0;i<7;i++)
{
JsonObject diet = new JsonObject();
diet["DayNumber"] = i;
diet["Breakfast"] = "Banana"+ i;
diet["Lunch"] = "Banana"+ i;
diet["Dinner"] = "Banana"+ i;
diet["WithSugar"] = (i % 2 == 0);
diet["RandomNumber"] = Random.Range(0f,1.5f);
weekDiet.Add(diet);
}
for (int i=0;i<7;i++)
{
if (i % 2 == 1)
{
weekDiet[i]["RandomNumber"] = 3;
weekDiet[i]["RandomNumber"] = weekDiet[i]["RandomNumber"] * 2f;
}
}
Debug.Log("Test InputOutputFileTest done: \n"+ weekDiet.ToJsonPrettyPrintString());
}
示例5: GetCategoryInfo
public void GetCategoryInfo(HttpContext context)
{
Func<Maticsoft.Model.SNS.Categories, bool> predicate = null;
string categoryId = context.Request.Params["CID"];
int type = Globals.SafeInt(context.Request.Params["Type"], 0);
JsonObject obj2 = new JsonObject();
if (!string.IsNullOrWhiteSpace(categoryId))
{
if (predicate == null)
{
predicate = c => c.ParentID == Globals.SafeInt(categoryId, 0);
}
List<Maticsoft.Model.SNS.Categories> list2 = this.SNSCateBll.GetAllCateByCache(type).Where<Maticsoft.Model.SNS.Categories>(predicate).ToList<Maticsoft.Model.SNS.Categories>();
if ((list2 != null) && (list2.Count > 0))
{
JsonArray data = new JsonArray();
list2.ForEach(delegate (Maticsoft.Model.SNS.Categories info) {
data.Add(new JsonObject(new string[] { "CategoryId", "Name", "ParentID", "HasChildren" }, new object[] { info.CategoryId, info.Name, info.ParentID, info.HasChildren }));
});
obj2.Put("STATUS", "Success");
obj2.Put("DATA", data);
}
else
{
obj2.Put("STATUS", "Fail");
}
}
else
{
obj2.Put("STATUS", "Error");
}
context.Response.Write(obj2.ToString());
}
示例6: GetAll
public JsonValue GetAll()
{
JsonObject parameters = WebOperationContext.Current.IncomingRequest.GetQueryStringAsJsonObject();
JsonValue term;
string termValue = parameters.TryGetValue("term", out term) ? term.ReadAs<string>() : String.Empty;
using (SqlConnection sc = new SqlConnection(connectionString))
{
sc.Open();
using (SqlCommand getAll = new SqlCommand("SELECT Email FROM Contact WHERE (Email LIKE @term)", sc))
{
getAll.Parameters.AddWithValue("@term", termValue + "%");
SqlDataReader reader = getAll.ExecuteReader();
JsonArray results = new JsonArray();
while (reader.Read())
{
results.Add(Convert.ToString(reader[0], CultureInfo.InvariantCulture));
}
return results;
}
}
}
示例7: LibraryResponse
protected override IJsonToken LibraryResponse(Library library)
{
JsonArray artists = new JsonArray();
foreach (Artist artist in library.GetArtists()) {
artists.Add(artist.ToJson());
}
return artists;
}
示例8: GetJson
JsonArray GetJson(IEnumerable<Song> songs)
{
JsonArray array = new JsonArray();
foreach (Song song in songs) {
array.Add(new JsonNumber(song.Id));
}
return array;
}
示例9: serializeArray
private static JsonArray serializeArray(IEnumerable arr)
{
Type elType;
JsonArray array = new JsonArray();
foreach (var el in arr)
{
elType = el.GetType();
JsonValueType valueType = JsonValue.GetPrimitiveType(elType);
if (valueType == JsonValueType.Object)
array.Add(serializeObject(el));
else if (valueType == JsonValueType.Array)
array.Add(serializeArray((IEnumerable)el));
else
array.Add(new JsonPrimitive(el.ToString(), valueType));
}
return array;
}
示例10: ContentDialog_PrimaryButtonClick
private async void ContentDialog_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args) {
var selected = new List<object>(TileList.SelectedItems);
var picker = new FileSavePicker();
picker.SuggestedFileName = $"export_{DateTime.Now.ToString(DateTimeFormatInfo.CurrentInfo.ShortDatePattern)}";
picker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
picker.FileTypeChoices.Add("Tiles file", new List<string>() { ".tiles" });
var file = await picker.PickSaveFileAsync();
if (file != null) {
CachedFileManager.DeferUpdates(file);
await FileIO.WriteTextAsync(file, "");
using (var stream = await file.OpenStreamForWriteAsync())
using (var zip = new ZipArchive(stream, ZipArchiveMode.Update)) {
while (zip.Entries.Count > 0) {
zip.Entries[0].Delete();
}
using (var metaStream = zip.CreateEntry("tiles.json").Open())
using (var writer = new StreamWriter(metaStream)) {
var array = new JsonArray();
selected.ForEachWithIndex<SecondaryTile>((item, index) => {
var objet = new JsonObject();
objet.Add("Name", item.DisplayName);
objet.Add("Arguments", item.Arguments);
objet.Add("TileId", item.TileId);
objet.Add("IconNormal", item.VisualElements.ShowNameOnSquare150x150Logo);
objet.Add("IconWide", item.VisualElements.ShowNameOnWide310x150Logo);
objet.Add("IconBig", item.VisualElements.ShowNameOnSquare310x310Logo);
array.Add(objet);
if (item.VisualElements.Square150x150Logo.LocalPath != DEFAULT_URI) {
var path = ApplicationData.Current.LocalFolder.Path + Uri.UnescapeDataString(item.VisualElements.Square150x150Logo.AbsolutePath.Substring(6));
zip.CreateEntryFromFile(path, item.TileId + "/normal");
}
});
writer.WriteLine(array.Stringify());
}
FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);
if(status == FileUpdateStatus.Complete) {
var folder = await file.GetParentAsync();
await new MessageDialog("Speichern erfolgreich").ShowAsync();
} else {
await new MessageDialog("Speichern fehlgeschlagen").ShowAsync();
}
Debug.WriteLine(status);
}
}
}
示例11: Invoke
//把函数转换出来的Json串交给后台数据库服务
public void Invoke(IAsyncObject obj, Func<JsonValue> method)
{
//传递到后台执行
Uri uri = new Uri(Uri);
WebClient client = new WebClient();
client.UploadStringCompleted += (o, e) =>
{
obj.IsBusy = false;
//通知数据提交过程完成
if (e.Error != null)
{
obj.State = State.Error;
obj.Error = e.Error.GetMessage();
}
else
{
//返回数据重新赋值给对象
JsonObject resultJson = (JsonObject)JsonValue.Parse(e.Result);
if (resultJson.ContainsKey(obj.Name))
{
(obj as IFromJson).FromJson((JsonObject)resultJson[obj.Name]);
}
//判定是否保存成功
if (resultJson.ContainsKey("success"))
{
string success = resultJson["success"];
MessageBox.Show(success);
}
if (resultJson.ContainsKey("error"))
{
obj.Error = resultJson["error"];
obj.State = State.Error;
obj.OnCompleted(e);
return;
}
else
{
obj.State = State.End;
}
}
obj.OnCompleted(e);
};
JsonArray array = new JsonArray();
JsonValue json = method();
if (json is JsonObject)
{
//把执行批处理对象的名字添加进去
json["name"] = obj.Name;
array.Add(json);
}
else
{
array = (JsonArray) json;
}
obj.IsBusy = true;
obj.State = State.Start;
client.UploadStringAsync(uri, array.ToString());
}
示例12: Main
static void Main(string[] args)
{
var inputString = @"{
""firstName"":""Иван"",
""lastName"":""Иванов"",
""test"":""test1\ntest2\ntest3\\"",
""address"":{
""streetAddress"":""Московское ш., 101, кв.101"",
""city"":""Ленинград"",
""postalCode"":101101
},
""phoneNumbers"":[
""812 123-1234"",
""916 123-4567""
]
}";
var json = (JsonObject)JsonParser.Parse(inputString);
Console.WriteLine("First name: {0}", json["firstName"]);
Console.WriteLine("Last name: {0}", json["lastName"]);
var address = (JsonObject)json["address"];
foreach (var el in address.Keys) Console.WriteLine("{0} = {1}", el, address[el]);
var phoneNumbers = (JsonArray)json["phoneNumbers"];
foreach (var el in phoneNumbers) Console.WriteLine("Phone: {0}", el);
var encodedJson = json.Encode();
var decodedJson = JsonParser.Parse(encodedJson);
Debug.Assert(encodedJson == decodedJson.Encode());
Console.WriteLine("Encoded JSON: {0}", encodedJson);
var testJson = new JsonObject();
testJson["hello"] = new JsonValue("world");
testJson["escaped_string"] = new JsonValue(@"Blabla""[123]\{abc}");
var author = new JsonObject();
author["name"] = new JsonValue("Cluster");
author["age"] = new JsonValue(26);
var contacts = new JsonArray();
contacts.Add(new JsonValue("http://clusterrr.com"));
contacts.Add(new JsonValue("[email protected]"));
author["contacts"] = contacts;
testJson["author"] = author;
encodedJson = testJson.Encode();
decodedJson = JsonParser.Parse(encodedJson);
Debug.Assert(encodedJson == decodedJson.Encode());
Console.WriteLine("Encoded JSON: {0}", encodedJson);
Console.ReadLine();
}
示例13: LibraryResponse
protected override IJsonToken LibraryResponse(Library library)
{
JsonArray array = new JsonArray();
SearchIndex index = new SearchIndex(library.GetSongs());
foreach (KeyValuePair<string, List<Song>> kvp in index) {
array.Add(GetJson(kvp.Key, kvp.Value));
}
return array;
}
示例14: ConvertToJson
public IJsonValue ConvertToJson(object instance)
{
Movie[] movies = (Movie[])instance;
JsonArray result = new JsonArray();
foreach (var movie in movies)
{
result.Add(MobileServiceTableSerializer.Serialize(movie));
}
return result;
}
示例15: GetAllUsers
public static JsonValue GetAllUsers(Cache cache)
{
var ret = new JsonArray();
foreach (var itm in cache)
{
if (itm is DictionaryEntry && ((DictionaryEntry)itm).Value is Tuple<string, string>)
{
ret.Add(GetUser(cache, ((DictionaryEntry)itm).Key.ToString()));
}
}
return ret;
}