/// <summary> /// Read JSON Array value. /// </summary> /// <param name="jsonReader">The <see cref="IJsonReader"/> to read from.</param> /// <returns>The <see cref="JsonArrayValue"/> generated.</returns> public static JsonArrayValue ReadAsArray(this IJsonReader jsonReader) { EdmUtil.CheckArgumentNull(jsonReader, "jsonReader"); // Supports to read from Begin if (jsonReader.NodeKind == JsonNodeKind.None) { jsonReader.Read(); } // Make sure the input is an Array jsonReader.ValidateNodeKind(JsonNodeKind.StartArray); JsonArrayValue arrayValue = new JsonArrayValue(); // Consume the "[" tag. jsonReader.Read(); while (jsonReader.NodeKind != JsonNodeKind.EndArray) { arrayValue.Add(jsonReader.ReadAsJsonValue()); } // Consume the "]" tag. jsonReader.Read(); return(arrayValue); }
/// <summary> /// Read <see cref="IJsonValue"/> to a string. /// </summary> /// <param name="jsonValue">The <see cref="IJsonValue"/> to parse from.</param> /// <returns>The string.</returns> public static string ReadAsJsonString(this IJsonValue jsonValue) { if (jsonValue == null) { throw new ArgumentNullException("jsonValue"); } // TODO: convert to use IJsonWriter if (jsonValue.ValueKind == JsonValueKind.Array) { bool first = true; JsonArrayValue arrayValue = (JsonArrayValue)jsonValue; StringBuilder sb = new StringBuilder("["); foreach (var item in arrayValue) { if (first) { first = false; } else { sb.Append(","); } sb.Append(item.ReadAsJsonString()); } sb.Append("]"); return(sb.ToString()); } else if (jsonValue.ValueKind == JsonValueKind.Object) { JsonObjectValue objectValue = (JsonObjectValue)jsonValue; StringBuilder sb = new StringBuilder("{"); bool first = true; foreach (var property in objectValue) { if (first) { first = false; } else { sb.Append(","); } sb.Append("\"" + property.Key + "\":"); sb.Append(property.Value.ReadAsJsonString()); } sb.Append("}"); return(sb.ToString()); } else { JsonPrimitiveValue primitiveValue = (JsonPrimitiveValue)jsonValue; if (primitiveValue.Value == null) { return("null"); } Type type = primitiveValue.Value.GetType(); if (type == typeof(bool)) { bool boolValue = (bool)primitiveValue.Value; if (boolValue) { return("true"); } return("false"); } if (type == typeof(int)) { int intValue = (int)primitiveValue.Value; return(intValue.ToString(CultureInfo.InvariantCulture)); } if (type == typeof(decimal)) { decimal decimalValue = (decimal)primitiveValue.Value; return(decimalValue.ToString(CultureInfo.InvariantCulture)); } if (type == typeof(double)) { double doubleValue = (double)primitiveValue.Value; return(doubleValue.ToString(CultureInfo.InvariantCulture)); } return("\"" + primitiveValue.Value.ToString() + "\""); } }