本文整理汇总了C#中Newtonsoft.Json.Linq.JObject.Merge方法的典型用法代码示例。如果您正苦于以下问题:C# JObject.Merge方法的具体用法?C# JObject.Merge怎么用?C# JObject.Merge使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Newtonsoft.Json.Linq.JObject
的用法示例。
在下文中一共展示了JObject.Merge方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: PostToIndex
private static void PostToIndex(IndexBlobMessage message, string productId)
{
var requestUri = new Uri(string.Format("{0}/indexes/{1}/docs/index?api-version={2}", message.Url, message.Name, message.ApiVersion));
// Construct JSON format for indexing
var indexObject = new JObject();
var indexObjectArray = new JArray();
var itemChild = new JObject { { "@search.action", "upload" } };
itemChild.Merge(message.Content);
indexObjectArray.Add(itemChild);
indexObject.Add("value", indexObjectArray);
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("api-key", message.AdminApiKey);
HttpResponseMessage result =
client.PostAsync(requestUri, new StringContent(indexObject.ToString()
, Encoding.UTF8, "application/json"))
.Result;
if (result.StatusCode == HttpStatusCode.OK)
{
Console.WriteLine("Uploaded product {0} to index '{1}'", productId, message.Name);
}
else
{
var err = string.Format("Document failed to upload: {0} \r\n",
result.Content.ReadAsStringAsync().Result);
throw new Exception(err);
}
}
}
示例2: LogException
public static JObject LogException(string errorMessage, Exception ex)
{
JObject result = new JObject();
result["type"] = "TimberWinR-Error";
result["ErrorMessage"] = errorMessage;
try
{
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
Formatting = Formatting.Indented,
NullValueHandling = NullValueHandling.Ignore
};
var exJson = JObject.Parse(JsonConvert.SerializeObject(ex));
result.Merge(exJson, new JsonMergeSettings
{
MergeArrayHandling = MergeArrayHandling.Replace
});
return result;
}
catch (Exception ex1)
{
result["ErrorMessage"] = ex1.ToString();
return result;
}
}
示例3: getParams
/// <summary>
/// Get the API request parameters.
/// </summary>
/// <returns></returns>
protected override JObject getParams()
{
var baseParameters = base.getParams();
var parameters = new JObject(consumerParams);
parameters.Merge(baseParameters);
parameters.Add(RublonAuthParams.FIELD_CALLBACK_URL, callbackUrl);
return parameters;
}
示例4: CombineJson
public static JObject CombineJson(JObject object1, JObject object2)
{
object1.Merge(object2, new JsonMergeSettings
{
MergeArrayHandling = MergeArrayHandling.Union
});
return object1;
}
示例5: GetLocalization
public JObject GetLocalization(string lang = "en")
{
var searchPattern = string.Format("{0}.*.json", lang);
var files = GetAllLocalizationFiles(searchPattern);
var result = new JObject();
foreach (var file in files)
{
var part = JObject.Parse(File.ReadAllText(file));
result.Merge(part, new JsonMergeSettings { MergeArrayHandling = MergeArrayHandling.Merge });
}
return result;
}
示例6: WriteJson
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
ContentItem contentItem = (ContentItem)value;
var o = new JObject();
// Write all well-known properties
o.Add(new JProperty(nameof(ContentItem.Id), contentItem.Id));
o.Add(new JProperty(nameof(ContentItem.ContentItemId), contentItem.ContentItemId));
o.Add(new JProperty(nameof(ContentItem.ContentType), contentItem.ContentType));
o.Add(new JProperty(nameof(ContentItem.Latest), contentItem.Latest));
o.Add(new JProperty(nameof(ContentItem.Number), contentItem.Number));
o.Add(new JProperty(nameof(ContentItem.Published), contentItem.Published));
// Write all custom content properties
o.Merge(contentItem.Data);
o.WriteTo(writer);
}
示例7: MergeNull
public void MergeNull()
{
JConstructor c = new JConstructor();
c.Merge(null);
Assert.AreEqual(null, c.Name);
Assert.AreEqual(0, c.Count);
JObject o = new JObject();
o.Merge(null);
Assert.AreEqual(0, o.Count);
JArray a = new JArray();
a.Merge(null);
Assert.AreEqual(0, a.Count);
JProperty p = new JProperty("name1");
p.Merge(null);
Assert.AreEqual("name1", p.Name);
Assert.AreEqual(0, p.Count);
}
示例8: Apply
public override bool Apply(JObject json)
{
if (!string.IsNullOrEmpty(Type))
{
JToken json_type = json["type"];
if (json_type != null && json_type.ToString() != Type)
return true; // Filter does not apply.
}
if (Condition != null)
{
var expr = EvaluateCondition(json, Condition);
if (!expr)
return true;
}
var source = json[Source];
if (source != null && !string.IsNullOrEmpty(source.ToString()))
{
try
{
var l = dr.City(source.ToString());
if (l != null)
{
JObject geo_json = new JObject(
new JProperty(Target,
new JObject(
new JProperty("ip", source.ToString()),
new JProperty("country_code2", l.Country.IsoCode),
new JProperty("country_name", l.Country.Name),
new JProperty("continent_code", l.Continent.Code),
new JProperty("region_name", l.MostSpecificSubdivision.IsoCode),
new JProperty("city_name", l.City.Name),
new JProperty("postal_code", l.Postal.Code),
new JProperty("latitude", l.Location.Latitude),
new JProperty("longitude", l.Location.Longitude),
new JProperty("dma_code", l.Location.MetroCode),
new JProperty("timezone", l.Location.TimeZone),
new JProperty("real_region_name", l.MostSpecificSubdivision.Name),
new JProperty("location",
new JArray(l.Location.Longitude, l.Location.Latitude)
))));
json.Merge(geo_json, new JsonMergeSettings
{
MergeArrayHandling = MergeArrayHandling.Union
});
}
else
{
json["_geoiperror"] = string.Format("IP Address not found: {0}", source.ToString());
}
}
catch (Exception ex)
{
json["_geoiperror"] = string.Format("IP Address not found: {0} ({1})", source.ToString(), ex.ToString());
return true;
}
}
AddFields(json);
AddTags(json);
RemoveFields(json);
RemoveTags(json);
return true;
}
示例9: MergeNullValue
public void MergeNullValue()
{
var source = new JObject
{
{"Property1", "value"},
{"Property2", new JObject()},
{"Property3", JValue.CreateNull()},
{"Property4", JValue.CreateUndefined()},
{"Property5", new JArray()}
};
var patch = JObject.Parse("{Property1: null, Property2: null, Property3: null, Property4: null, Property5: null}");
source.Merge(patch, new JsonMergeSettings
{
MergeNullValueHandling = MergeNullValueHandling.Merge
});
Assert.IsNotNull(source["Property1"]);
Assert.AreEqual(JTokenType.Null, source["Property1"].Type);
Assert.IsNotNull(source["Property2"]);
Assert.AreEqual(JTokenType.Null, source["Property2"].Type);
Assert.IsNotNull(source["Property3"]);
Assert.AreEqual(JTokenType.Null, source["Property3"].Type);
Assert.IsNotNull(source["Property4"]);
Assert.AreEqual(JTokenType.Null, source["Property4"].Type);
Assert.IsNotNull(source["Property5"]);
Assert.AreEqual(JTokenType.Null, source["Property5"].Type);
}
示例10: BuildJson
string BuildJson(IEnumerable<ParameterItemViewModel> items)
{
var root = new JObject();
foreach (var item in items)
{
var split = item.Name.Split('.').Skip(1).ToArray(); // first is container name, ignore
JObject rootJo = null;
Array.Reverse(split);
for (int i = 0; i < split.Length; i++)
{
// Last
if (i == 0)
{
var o = new JObject();
o.Add(split[i], GetJToken(item.TypeName, item.ParameterValue.Value));
rootJo = o;
}
else
{
// append child
var o = new JObject();
o.Add(split[i], rootJo);
rootJo = o;
}
}
root.Merge(rootJo); // Merge Json
}
return root.ToString(Formatting.None);
}
示例11: GetConfigurations
private static void GetConfigurations(string configdir, JObject configSettings)
{
foreach (var configFile in Directory.GetFiles(configdir, "*.json"))
{
try {
using (var envReader = new StreamReader(configFile))
{
using (var envJsonReader = new JsonTextReader(envReader))
{
var current = (JObject)JToken.ReadFrom(envJsonReader);
configSettings.Merge(current, new JsonMergeSettings
{ MergeArrayHandling = MergeArrayHandling.Merge });
}
}
}
catch (Exception e)
{
Log.Warn("Error while reading JSON file {0} and will be ignored: {1}", configFile, e);
}
}
}
示例12: Apply
public override bool Apply(JObject json)
{
if (!string.IsNullOrEmpty(Type))
{
JToken json_type = json["type"];
if (json_type != null && json_type.ToString() != Type)
return true; // Filter does not apply.
}
if (Condition != null)
{
var expr = EvaluateCondition(json, Condition);
if (!expr)
return true;
}
var source = json[Source];
if (source == null)
return true;
var jsonOrig = source.ToString();
if (!string.IsNullOrEmpty(source.ToString()))
{
try
{
JObject subJson;
if (Target != null && !string.IsNullOrEmpty(Target))
{
subJson = new JObject();
subJson[Target] = JObject.Parse(source.ToString());
}
else
subJson = JObject.Parse(source.ToString());
if (!string.IsNullOrEmpty(Promote))
{
var promotedJson = subJson[Promote];
RemoveProperties(subJson, new string[] { Promote });
subJson.Merge(promotedJson, new JsonMergeSettings
{
MergeArrayHandling = MergeArrayHandling.Replace
});
}
json.Merge(subJson, new JsonMergeSettings
{
MergeArrayHandling = MergeArrayHandling.Replace
});
if (Rename != null && Rename.Length > 0)
{
for (int i = 0; i < Rename.Length; i += 2)
{
string oldName = ExpandField(Rename[i], json);
string newName = ExpandField(Rename[i+1], json);
RenameProperty(json, oldName, newName);
}
}
if (RemoveSource)
{
RemoveProperties(json, new string[] { Source });
}
}
catch (Exception ex)
{
LogManager.GetCurrentClassLogger().Error(ex);
Interlocked.Increment(ref _errorCount);
return true;
}
}
AddFields(json);
AddTags(json);
RemoveFields(json);
RemoveTags(json);
return true;
}
示例13: MergeHsanFiles
public static void MergeHsanFiles(string srcPath, string songPackName, string destPath)
{
//Load hsan manifest
var hsanFiles = Directory.EnumerateFiles(srcPath, "*.hsan", SearchOption.AllDirectories).ToArray();
if (hsanFiles.Length < 1)
throw new DataException("No songs_*.hsan file found.");
// merge multiple hsan files into a single hsan file
if (hsanFiles.Length > 1)
{
var mergeSettings = new JsonMergeSettings { MergeArrayHandling = MergeArrayHandling.Union };
JObject hsanObject1 = new JObject();
foreach (var hsan in hsanFiles)
{
JObject hsanObject2 = JObject.Parse(File.ReadAllText(hsan));
hsanObject1.Merge(hsanObject2, mergeSettings);
}
var hsanFileName = String.Format("songs_dlc_{0}.hsan", songPackName.ToLower());
var hsanPath = Path.Combine(destPath, hsanFileName);
string json = JsonConvert.SerializeObject(hsanObject1, Formatting.Indented);
File.WriteAllText(hsanPath, json);
// delete old hsan files
foreach (var hsan in hsanFiles)
File.Delete(hsan);
}
}
示例14: WriteSingleFile
private bool WriteSingleFile(LanguageData data, string dstPath)
{
var root = new JObject();
var groups = data.GroupBy(o => o.Namespace);
foreach (var g in groups)
{
var namespaces = g.Key.Split('.');
var prev = new JObject(g.Select(o => new JProperty(o.Key, o.Value)));
foreach (var ns in namespaces.Reverse())
{
var temp = new JObject(new JProperty(ns, prev));
prev = temp;
}
// 各グループ要素を、全体のJSONオブジェクトにマージ
root.Merge(prev);
}
File.WriteAllText(dstPath, root.ToString());
return true;
}
示例15: RS1LoadFromFolder
// Load RS1 CDLC into PackageCreator
public static DLCPackageData RS1LoadFromFolder(string unpackedDir, Platform targetPlatform, bool convert)
{
var data = new DLCPackageData();
data.Arrangements = new List<Arrangement>();
data.TonesRS2014 = new List<Tone2014>();
data.Tones = new List<Tone>();
data.GameVersion = (convert ? GameVersion.RS2014 : GameVersion.RS2012);
data.SignatureType = PackageMagic.CON;
// set default volumes
data.Volume = -6.5F; // default maybe too quite
data.PreviewVolume = data.Volume;
//Load song manifest
var songsManifestJson = Directory.GetFiles(unpackedDir, "songs.manifest.json", SearchOption.AllDirectories);
if (songsManifestJson.Length < 1)
throw new DataException("No songs.manifest.json file found.");
if (songsManifestJson.Length > 1)
throw new DataException("More than one songs.manifest.json file found.");
var attr = new List<Attributes>();
var songsManifest = Manifest.Manifest.LoadFromFile(songsManifestJson[0]).Entries.ToArray();
for (int smIndex = 0; smIndex < songsManifest.Count(); smIndex++)
{
var smData = songsManifest[smIndex].Value.ToArray()[0].Value;
attr.Add(smData);
}
if (attr.FirstOrDefault() == null)
throw new DataException("songs.manifest.json file did not parse correctly.");
// Fill SongInfo
data.SongInfo = new SongInfo();
data.SongInfo.SongDisplayName = attr.FirstOrDefault().SongName;
data.SongInfo.SongDisplayNameSort = attr.FirstOrDefault().SongNameSort;
data.SongInfo.Album = attr.FirstOrDefault().AlbumName;
data.SongInfo.SongYear = (attr.FirstOrDefault().SongYear == 0 ? 2012 : attr.FirstOrDefault().SongYear);
data.SongInfo.Artist = attr.FirstOrDefault().ArtistName;
data.SongInfo.ArtistSort = attr.FirstOrDefault().ArtistNameSort;
data.Name = attr.FirstOrDefault().SongKey;
//Load tone manifest, even poorly formed tone_bass.manifest.json
var toneManifestJson = Directory.GetFiles(unpackedDir, "*tone*.manifest.json", SearchOption.AllDirectories);
if (toneManifestJson.Length < 1)
throw new DataException("No tone.manifest.json file found.");
// toolkit produces multiple tone.manifest.json files when packing RS1 CDLC files
// rather than change toolkit behavior just merge manifest files for now
if (toneManifestJson.Length > 1)
{
var mergeSettings = new JsonMergeSettings { MergeArrayHandling = MergeArrayHandling.Union };
JObject toneObject1 = new JObject();
foreach (var tone in toneManifestJson)
{
JObject toneObject2 = JObject.Parse(File.ReadAllText(tone));
//(toneObject1.SelectToken("Entries") as JArray).Merge(toneObject2.SelectToken("Entries"));
toneObject1.Merge(toneObject2, mergeSettings);
}
toneManifestJson = new string[1];
toneManifestJson[0] = Path.Combine(unpackedDir, "merged.tone.manifest.json");
string json = JsonConvert.SerializeObject(toneObject1, Formatting.Indented);
File.WriteAllText(toneManifestJson[0], json);
}
var tones2014 = new List<Tone2014>();
var tones = new List<Tone>();
var toneManifest = Manifest.Tone.Manifest.LoadFromFile(toneManifestJson[0]);
for (int tmIndex = 0; tmIndex < toneManifest.Entries.Count(); tmIndex++)
{
var tmData = toneManifest.Entries[tmIndex];
tones.Add(tmData);
}
data.Tones = tones;
// Load AggregateGraph.nt
var songDir = Path.Combine(unpackedDir, data.Name);
if (targetPlatform.platform == GamePlatform.XBox360)
songDir = Path.Combine(unpackedDir, "Root", data.Name);
var aggFile = Directory.GetFiles(songDir, "*.nt", SearchOption.TopDirectoryOnly)[0];
var aggGraphData = AggregateGraph.AggregateGraph.ReadFromFile(aggFile);
// Load Exports\Songs\*.xblock
var xblockDir = Path.Combine(songDir, "Exports\\Songs");
var xblockFile = Directory.GetFiles(xblockDir, "*.xblock", SearchOption.TopDirectoryOnly)[0];
// xblockFile = "D:\\Temp\\Mapping\\songs.xblock";
var songsXblock = XblockX.LoadFromFile(xblockFile);
// create project map for cross referencing arrangements with tones
var projectMap = AggregateGraph.AggregateGraph.ProjectMap(aggGraphData, songsXblock, toneManifest);
// Load xml arrangements
var xmlFiles = Directory.GetFiles(unpackedDir, "*.xml", SearchOption.AllDirectories);
if (xmlFiles.Length <= 0)
//.........这里部分代码省略.........