本文整理汇总了C#中JsonObject.ToJson方法的典型用法代码示例。如果您正苦于以下问题:C# JsonObject.ToJson方法的具体用法?C# JsonObject.ToJson怎么用?C# JsonObject.ToJson使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类JsonObject
的用法示例。
在下文中一共展示了JsonObject.ToJson方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Generate
internal static JsonObject Generate(Comment comment, ServerInfo serverInfo)
{
var json = new JsonObject();
if (comment.Body != null)
{
json.Add("body", comment.Body);
}
if (comment.Visibility != null)
{
if (serverInfo.BuildNumber >= ServerVersionConstants.BuildNumberJira43)
{
var visibilityJson = new JsonObject();
var commentVisibilityType = comment.Visibility.Type == Visibility.VisibilityType.Group ? "group" : "role";
if (serverInfo.BuildNumber < ServerVersionConstants.BuildNumberJira5)
{
commentVisibilityType = commentVisibilityType.ToUpper();
}
visibilityJson.Add("type", commentVisibilityType);
visibilityJson.Add("value", comment.Visibility.Value);
json.Add("visibility", visibilityJson.ToJson());
}
else
{
json.Add(comment.Visibility.Type == Visibility.VisibilityType.Role ? "role" : "group", comment.Visibility.Value);
}
}
return json;
}
示例2: DoAction
protected override void DoAction()
{
int projectId = Convert.ToInt32(GetParam("deployId"));
int pageSize;
if (!int.TryParse(GetParam("pageSize"), out pageSize))
{
pageSize = 10;
}
List<DepProjectAction> projectList = SvnProcesser.DeployLog(projectId, pageSize);
JsonObject jsonContainer = new JsonObject();
List<JsonObject> jsonList = new List<JsonObject>();
foreach (var item in projectList)
{
JsonObject jItem = new JsonObject();
jItem.Add("Id", item.Id);
jItem.Add("Ip", item.Ip);
jItem.Add("DepId", item.DepId);
jItem.Add("Type", item.Type);
jItem.Add("Revision", item.Revision);
jItem.Add("Status", item.Status);
jItem.Add("ErrorMsg", FormatJson(item.ErrorMsg));
jItem.Add("CreateDate", item.CreateDate.ToString("yyyy-MM-dd HH:mm:ss"));
jsonList.Add(jItem);
}
jsonContainer.Add("rows", jsonList.ToArray());
string comboJson = jsonContainer.ToJson();
_context.Response.Write(comboJson);
}
示例3: DoAction
protected override void DoAction()
{
List<DepProject> projectList = SvnProcesser.ProjectList();
JsonObject jsonContainer = new JsonObject();
List<JsonObject> jsonList = new List<JsonObject>();
foreach (var item in projectList)
{
JsonObject jItem = new JsonObject();
jItem.Add("SlnId", item.Id);
jItem.Add("SlnName", item.Name);
jItem.Add("Ip", item.Ip);
jItem.Add("SvnPath", item.SvnPath);
jItem.Add("SharePath", item.SharePath);
jItem.Add("ExcludeFile", item.ExcludeFile);
jItem.Add("CreateDate", item.CreateDate.ToString("yyyy-MM-dd HH:mm:ss"));
jItem.Add("GameId", item.GameId);
jsonList.Add(jItem);
}
jsonContainer.Add("rows", jsonList.ToArray());
string comboJson = jsonContainer.ToJson();
_context.Response.Write(comboJson);
}
示例4: DoAction
protected override void DoAction()
{
if (hasDoAction)
{
return;
}
int projectId = Convert.ToInt32(GetParam("deployId"));
List<DepProjectItem> projectList = SvnProcesser.ProjectItemList(projectId);
JsonObject jsonContainer = new JsonObject();
List<JsonObject> jsonList = new List<JsonObject>();
foreach (var item in projectList)
{
JsonObject jItem = new JsonObject();
jItem.Add("Id", item.Id);
jItem.Add("Name", item.Name);
jItem.Add("WebSite", item.WebSite);
jItem.Add("DeployPath", item.DeployPath);
jItem.Add("ExcludeFile", item.ExcludeFile);
jItem.Add("CreateDate", item.CreateDate.ToString("yyyy-MM-dd HH:mm:ss"));
jItem.Add("ServerId", item.ServerId);
jsonList.Add(jItem);
}
jsonContainer.Add("rows", jsonList.ToArray());
string comboJson = jsonContainer.ToJson();
_context.Response.Write(comboJson);
}
示例5: Generate
/// <summary>
/// Generates the JSON.
/// </summary>
/// <param name="fieldChanges">The changes to make to the issue.</param>
/// <returns>The JSON.</returns>
internal static JsonObject Generate(IList<UpdateFieldInput> fieldChanges)
{
var jsonObject = new JsonObject();
var list = new JsonObject();
if (fieldChanges != null)
{
foreach (var change in fieldChanges)
{
list.Add(change.Field.ToRestString(), change.Elements.ConvertAll(a => new JsonObject { { a.Operation.ToRestString(), a.Value.ToString() } }).ToJson());
}
}
jsonObject.Add("update", list.ToJson());
return jsonObject;
}
示例6: Generate
internal static JsonObject Generate(TransitionInput transitionInput, ServerInfo serverInfo)
{
var jsonObject = new JsonObject();
if (serverInfo.BuildNumber >= ServerVersionConstants.BuildNumberJira5)
{
var id = new JsonObject { { "id", transitionInput.Id.ToString() } };
jsonObject.Add("transition", id.ToJson());
}
else
{
jsonObject.Add("transition", transitionInput.Id.ToString());
}
if (transitionInput.Comment != null)
{
var comment = CommentJsonGenerator.Generate(transitionInput.Comment, serverInfo).ToJson();
if (serverInfo.BuildNumber >= ServerVersionConstants.BuildNumberJira5)
{
var jsonComment = new JsonArrayObjects { new JsonObject { { "add", comment } } };
var jsonUpdate = new JsonObject { { "comment", jsonComment.ToJson() } };
jsonObject.Add("update", jsonUpdate.ToJson());
}
else
{
jsonObject.Add("comment", comment);
}
}
if (transitionInput.Fields != null && transitionInput.Fields.Any())
{
var list = transitionInput.Fields.Where(f => f.Value != null).ToDictionary(f => f.Id, f => ComplexIssueInputFieldValueJsonGenerator.GenerateFieldValueForJson(f.Value));
jsonObject.Add("fields", list.ToJson());
}
return jsonObject;
}
示例7: findTrainStationById
private byte[] findTrainStationById(NameValueCollection boundVariables,
JsonObject operationInput,
string outputFormat,
string requestProperties,
out string responseProperties)
{
responseProperties = null;
string IdValue;
bool found = operationInput.TryGetString("trainStationId", out IdValue);
if (!found || string.IsNullOrEmpty(IdValue))
throw new ArgumentNullException("trainStationId");
JsonObject result = new JsonObject();
result.AddString("stationName", "Train Station " + IdValue);
return Encoding.UTF8.GetBytes(result.ToJson());
}
示例8: NumberOfTrainStationsResHandler
private byte[] NumberOfTrainStationsResHandler(NameValueCollection boundVariables, string outputFormat, string requestProperties, out string responseProperties)
{
responseProperties = "{\"Content-Type\" : \"application/json\"}";
JsonObject result = new JsonObject();
result.AddString("numberOfTrainStations", "100");
return Encoding.UTF8.GetBytes(result.ToJson());
}
示例9: editFeatureOperHandler
private byte[] editFeatureOperHandler(NameValueCollection boundVariables,
JsonObject operationInput,
string outputFormat,
string requestProperties,
out string responseProperties)
{
responseProperties = null;
// get the id of the feature to be edited
object featureIdObj;
operationInput.TryGetObject("featureId", out featureIdObj);
int updateFeatureId = Convert.ToInt32(featureIdObj.ToString());
object featureJSONObj;
operationInput.TryGetObject("featureJSON", out featureJSONObj);
JsonObject updateFeatureJSON = (JsonObject)featureJSONObj;
// set a filter for the specific feature
QueryFilter queryFilter = new QueryFilter();
if (this.fc == null)
{
return createErrorObject(
406,
"Incorrect layer id provided.",
new String[] { "Please provide layer id of a feature layer." });
}
IClass myClass = (IClass) this.fc;
queryFilter.WhereClause = myClass.OIDFieldName + "=" + updateFeatureId;
IFeatureCursor featureCursor = this.fc.Search(queryFilter, false);
// attempt retrieval of the feature and check if it does exist
IFeatureCursor myFeatureCursor = (IFeatureCursor) featureCursor;
IFeature updateFeature = myFeatureCursor.NextFeature();
if (updateFeature == null) {
return createErrorObject(
406,
"Incorrect feature id provided.",
new String[] { "No feature exists for feature id "
+ updateFeatureId + "." });
}
JsonObject response = new JsonObject();
// edit feature
string result = System.Text.Encoding.GetEncoding("utf-8").GetString(performEdits(updateFeature, updateFeatureJSON));
featureCursor.Flush();
if (result.Equals(System.Boolean.TrueString))
{
response.AddString("status", "success");
response.AddString("message", "Feature " + updateFeatureId + " updated");
}
else
{
response.AddString("status", "failure");
response.AddString("message", result);
}
// send response back to client app
return Encoding.UTF8.GetBytes(response.ToJson());
}
示例10: addNewFeatureOperHandler
private byte[] addNewFeatureOperHandler(NameValueCollection boundVariables,
JsonObject operationInput,
string outputFormat,
string requestProperties,
out string responseProperties)
{
responseProperties = null;
// get the feature JSON
JsonObject newFeatureJSON = null;
operationInput.TryGetJsonObject("featureJSON", out newFeatureJSON);
// add the new feature
IFeature newFeature;
var bytes = addFeature(newFeatureJSON, out newFeature);
if (null == newFeature)
return bytes; //return error
// send response back to client app
var response = new JsonObject();
response.AddString("status", "success");
response.AddString("message", "Feature " + newFeature.OID + " added.");
return Encoding.UTF8.GetBytes(response.ToJson());
}
示例11: QueryPoint
private byte[] QueryPoint(ESRI.ArcGIS.Geometry.IPoint location, double distance)
{
if (distance <= 0.0)
throw new ArgumentOutOfRangeException("distance");
// Buffer the point.
ITopologicalOperator topologicalOperator = (ESRI.ArcGIS.Geometry.ITopologicalOperator)location;
IGeometry queryGeometry = topologicalOperator.Buffer(distance);
// Query the feature class.
ISpatialFilter spatialFilter = new ESRI.ArcGIS.Geodatabase.SpatialFilter();
spatialFilter.Geometry = queryGeometry;
spatialFilter.SpatialRel = ESRI.ArcGIS.Geodatabase.esriSpatialRelEnum.esriSpatialRelIntersects;
spatialFilter.GeometryField = m_fcToQuery.ShapeFieldName;
IFeatureCursor resultsFeatureCursor = m_fcToQuery.Search(spatialFilter, true);
// Loop through the features, clip each geometry to the buffer
// and total areas by attribute value.
topologicalOperator = (ESRI.ArcGIS.Geometry.ITopologicalOperator)queryGeometry;
int classFieldIndex = m_fcToQuery.FindField(m_mapFieldToQuery);
// System.Collections.Specialized.ListDictionary summaryStatsDictionary = new System.Collections.Specialized.ListDictionary();
Dictionary<string, double> summaryStatsDictionary = new Dictionary<string, double>();
// Initialize a list to hold JSON geometries.
List<JsonObject> jsonGeometries = new List<JsonObject>();
IFeature resultsFeature = null;
while ((resultsFeature = resultsFeatureCursor.NextFeature()) != null)
{
// Clip the geometry.
IPolygon clippedResultsGeometry = (IPolygon)topologicalOperator.Intersect(resultsFeature.Shape,
ESRI.ArcGIS.Geometry.esriGeometryDimension.esriGeometry2Dimension);
clippedResultsGeometry.Densify(0, 0); // Densify to maintain curved appearance when converted to JSON.
// Convert the geometry to JSON and add it to the list.
JsonObject jsonClippedResultsGeometry = Conversion.ToJsonObject(clippedResultsGeometry);
jsonGeometries.Add(jsonClippedResultsGeometry);
// Get statistics.
IArea area = (IArea)clippedResultsGeometry;
string resultsClass = resultsFeature.get_Value(classFieldIndex) as string;
// If the class is already in the dictionary, add the current feature's area to the existing entry.
if (summaryStatsDictionary.ContainsKey(resultsClass))
summaryStatsDictionary[resultsClass] = (double)summaryStatsDictionary[resultsClass] + area.Area;
else
summaryStatsDictionary[resultsClass] = area.Area;
}
// Use a helper method to get a JSON array of area records.
JsonObject[] areaResultJson = CreateJsonRecords(summaryStatsDictionary) as JsonObject[];
// Create a JSON object of the geometry results and the area records.
JsonObject resultJsonObject = new JsonObject();
resultJsonObject.AddArray("geometries", jsonGeometries.ToArray());
resultJsonObject.AddArray("records", areaResultJson);
// Get byte array of json and return results.
byte[] result = Encoding.UTF8.GetBytes(resultJsonObject.ToJson());
return result;
}
示例12: CreateEncryptedJweToken
public static string CreateEncryptedJweToken(JsonObject jwtPayload, RSAParameters publicKey)
{
//From: http://self-issued.info/docs/draft-ietf-jose-json-web-encryption-09.html#RSACBCExample
var jweHeader = new JsonObject
{
{ "alg", "RSA-OAEP" },
{ "enc", "A128CBC-HS256" },
{ "kid", Convert.ToBase64String(publicKey.Modulus).Substring(0,3) },
};
var jweHeaderBase64Url = jweHeader.ToJson().ToUtf8Bytes().ToBase64UrlSafe();
var authKey = new byte[128 / 8];
var cryptKey = new byte[128 / 8];
var cryptAuthKeys256 = AesUtils.CreateKey();
Buffer.BlockCopy(cryptAuthKeys256, 0, authKey, 0, authKey.Length);
Buffer.BlockCopy(cryptAuthKeys256, authKey.Length, cryptKey, 0, cryptKey.Length);
var aes = Aes.Create();
aes.KeySize = 128;
aes.BlockSize = 128;
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
using (aes)
{
aes.GenerateIV();
var iv = aes.IV;
aes.Key = cryptKey;
var jweEncKey = RsaUtils.Encrypt(cryptAuthKeys256, publicKey, UseRsaKeyLength);
var jweEncKeyBase64Url = jweEncKey.ToBase64UrlSafe();
var ivBase64Url = iv.ToBase64UrlSafe();
var aad = jweHeaderBase64Url + "." + jweEncKeyBase64Url;
var aadBytes = aad.ToUtf8Bytes();
var payloadBytes = jwtPayload.ToJson().ToUtf8Bytes();
byte[] cipherText, tag;
using (var encrypter = aes.CreateEncryptor(cryptKey, iv))
using (var cipherStream = new MemoryStream())
{
using (var cryptoStream = new CryptoStream(cipherStream, encrypter, CryptoStreamMode.Write))
using (var writer = new BinaryWriter(cryptoStream))
{
writer.Write(payloadBytes);
}
cipherText = cipherStream.ToArray();
}
using (var hmac = new HMACSHA256(authKey))
using (var encryptedStream = new MemoryStream())
{
using (var writer = new BinaryWriter(encryptedStream))
{
writer.Write(aadBytes);
writer.Write(iv);
writer.Write(cipherText);
writer.Flush();
tag = hmac.ComputeHash(encryptedStream.ToArray());
}
}
var cipherTextBase64Url = cipherText.ToBase64UrlSafe();
var tagBase64Url = tag.ToBase64UrlSafe();
var jweToken = jweHeaderBase64Url + "."
+ jweEncKeyBase64Url + "."
+ ivBase64Url + "."
+ cipherTextBase64Url + "."
+ tagBase64Url;
return jweToken;
}
}
示例13: RootResHandler
private byte[] RootResHandler(NameValueCollection boundVariables, string outputFormat, string requestProperties, out string responseProperties)
{
responseProperties = null;
IServerEnvironment3 senv = GetServerEnvironment() as IServerEnvironment3;
JsonObject result = new JsonObject();
JsonObject suinfoj = new JsonObject();
//get user info and serialize into JSON
IServerUserInfo suinfo = senv.UserInfo;
if (null != suinfo)
{
suinfoj.AddString("currentUser", suinfo.Name);
IEnumBSTR roles = suinfo.Roles;
List<string> rolelist = new List<string>();
if (null != roles)
{
string role = roles.Next();
while (!string.IsNullOrEmpty(role))
{
rolelist.Add(role);
role = roles.Next();
}
}
suinfoj.AddArray("roles", rolelist.ToArray());
result.AddJsonObject("serverUserInfo", suinfoj);
}
else
{
result.AddJsonObject("serverUserInfo", null);
}
return Encoding.UTF8.GetBytes(result.ToJson());
}
示例14: GetIdsOfLayersThatHaveMetadata
/// <summary>
/// Returns a JSON serialized array listing all of the feature layers in the map service, converted to a byte array.
/// </summary>
/// <param name="boundVariables">Not used by this method, but required for method signature..</param>
/// <param name="outputFormat">The only supported format is "json".</param>
/// <param name="requestProperties">Not used by this method, but required for method signature.</param>
/// <param name="responseProperties">Not used by this method, but required for method signature</param>
/// <returns></returns>
private byte[] GetIdsOfLayersThatHaveMetadata(NameValueCollection boundVariables,
string outputFormat,
string requestProperties,
out string responseProperties)
{
responseProperties = null;
var idArray = GetIdsOfLayersThatHaveMetadata();
JsonObject output = new JsonObject();
output.AddArray("layerIds", idArray.Select(i => i as object).ToArray());
return Encoding.UTF8.GetBytes(output.ToJson());
}
示例15: GetRasterStatisticsOperHandler
/*
*该函数用来实现对影像服务中的影像进行统计,统计各波段值中的最大最小值
*
*
*/
private byte[] GetRasterStatisticsOperHandler(NameValueCollection boundVariables,
JsonObject operationInput,
string outputFormat,
string requestProperties,
out string responseProperties)
{
_logger.LogMessage(ServerLogger.msgType.infoDetailed, _soename + ".GetRasterStatistics", 8000, "request received");
if (!_supportRasterItemAccess)
throw new ArgumentException("The image service does not have a catalog and does not support this operation");
responseProperties = null;
long? objectID;
//case insensitive
bool found = operationInput.TryGetAsLong("objectID", out objectID);
if (!found || (objectID == null))
throw new ArgumentNullException("ObjectID");
IRasterCatalogItem rasterCatlogItem = null;
IRasterBandCollection rasterBandsCol = null;
IRasterStatistics statistics = null;
try
{
//获取栅格目录
rasterCatlogItem = _mosaicCatalog.GetFeature((int)objectID) as IRasterCatalogItem;
if (rasterCatlogItem == null)
{
_logger.LogMessage(ServerLogger.msgType.infoDetailed, _soename + ".GetRasterStatistics", 8000, "request finished with exception");
throw new ArgumentException("The input ObjectID does not exist");
}
}
catch
{
_logger.LogMessage(ServerLogger.msgType.infoDetailed, _soename + ".GetRasterStatistics", 8000, "request finished with exception");
throw new ArgumentException("The input ObjectID does not exist");
}
JsonObject result = new JsonObject();
try
{
rasterBandsCol = (IRasterBandCollection)rasterCatlogItem.RasterDataset;
List<object> maxvalues = new List<object>();
List<object> minvalues = new List<object>();
List<object> standarddeviationvalues = new List<object>();
List<object> meanvalues = new List<object>();
for (int i = 0; i < rasterBandsCol.Count; i++)
{
statistics = rasterBandsCol.Item(i).Statistics;
maxvalues.Add(statistics.Maximum);
minvalues.Add(statistics.Minimum);
standarddeviationvalues.Add(statistics.StandardDeviation);
meanvalues.Add(statistics.Mean);
Marshal.ReleaseComObject(statistics);
}
//结果序列号
result.AddArray("maxValues", maxvalues.ToArray());
result.AddArray("minValues", minvalues.ToArray());
result.AddArray("meanValues", meanvalues.ToArray());
result.AddArray("stdvValues", standarddeviationvalues.ToArray());
}
catch
{
_logger.LogMessage(ServerLogger.msgType.infoDetailed, "GetRasterStatistics", 8000, "request completed. statistics does not exist");
}
finally
{
if (rasterBandsCol != null)
Marshal.ReleaseComObject(rasterBandsCol);
if (rasterCatlogItem != null)
Marshal.ReleaseComObject(rasterCatlogItem);
}
_logger.LogMessage(ServerLogger.msgType.infoDetailed, _soename + ".GetRasterStatistics", 8000, "request completed successfully");
return Encoding.UTF8.GetBytes(result.ToJson());
}