I'm working with an API rest and it returns me two types of json, object and array.
Object(When there is only one record in the database):
{ "complain": { "id": "1" , "description": "hello", "date": "2017-01-24 11:46:22", "Lat": "20.5204446", "Long": "-100.8249097" } }
Array(When there is more than one record in the database):
{ "complain": [ { "id": "1" , "description": "hello", "date": "2017-01-24 11:46:22", "Lat": "20.587446", "Long": "-100.8246490" }, { "id": "2" , "description": "hello 2", "date": "2017-01-24 11:50:12", "Lat": "20.529876", "Long": "-100.8249097" } ] }
The code I use to consume the json is as follows:
content = await response.Content.ReadAsStringAsync();
var token = JToken.Parse(content);
if (token["complain"] is JArray)
{
var jsonArray = JsonConvert.DeserializeObject<RootArray>(content);
}
else if (token["complain"] is JObject)
{
var jsonObject = JsonConvert.DeserializeObject<RootObject>(content);
}
When it comes to a json array if I can add it to a listview:
myList.ItemsSource = jsonArray.listArray;
But if it is an object I can not and I get the following error:
Cannot implicitly convert type Object to IEnumerable.
Finally I was able to solve my error, it was just a matter of creating a list and adding the deserialized json object.
var jsonObject = JsonConvert.DeserializeObject<RootObject>(content);
List<Complain> simpleList = new List<Complain>();
simpleList.Add(jsonObject.ComplainObject);
myList.ItemsSource = simpleList;
The class to deserialize the Json object:
public class RootObject
{
[JsonProperty("complain")]
public Complain ComplainObject { get; set; }
}
Related
I have built a controller which returns a list of objects
fun getUserCommunicationSettings(
#PathVariable commId: String,
#CommunicationTypeConstraint #RequestParam(required = false) commType: CommunicationType?
): ResponseEntity<out UserCommResponse> {
return communicationSettingsService.getUserCommSettings(commType, commId)
.mapError { mapUserCommErrorToResponse(it) }
.map { ResponseEntity.ok(SuccessResponse(it)) }
.fold<ResponseEntity<SuccessResponse<List<CommunicationSettingsDto>>>, ResponseEntity<ErrorResponse>, ResponseEntity<out UserCommResponse>>(
{ it },
{ it },
)
}
problem is it returns the following json with "entity" tag which i'd like to get rid of
{
"entity": [
{
"userId": "1075",
"userType": "CUSTOMER",
"communicationId": "972547784682",
"communicationType": "CALL",
"messageType": "CALL_COLLECTION"
}
]
}
any ideas?
I am working on upgrading a service from ES 5.0 to 6.8. I have a bucket aggregate that in v5 serializes to this:
"items": [
{
"key": "random+topic",
"docCount": 27919,
"aggregations": {
"ParentReference": {
"docCount": 24992,
"aggregations": {
"Popularity": {
"value": 25223
}
}
}
}
},
{
"key": "unknown problem+latency",
"docCount": 24566,
"aggregations": {
"ParentReference": {
"docCount": 23419,
"aggregations": {
"Popularity": {
"value": 23931
}
}
}
}
},
With the v6 of Elasticsearch.Net and Nest, when serialized, I end up with:
"items": [
{
"ParentReference": {
"Popularity": {
"value": 25223
}
}
},
{
"ParentReference": {
"Popularity": {
"value": 23931
}
}
},
I had previously encountered the issue where the "aggregations" property is no longer returned (though I would love a pointer to the breaking changes announcement on that), and have updated my code accordingly. I can't do much without the Key and docCount, however. I figure there must be something related to the Json parsing changes.
I have already tried the steps in:
Custom Serialization | Elasticsearch.Net and NEST: the .NET clients [6.x] | Elastic
I have tried with the default serializer, as well as a custom one using the JsonNetSerializer.Default to no effect.
Can anyone provide a suggestion on what I should be doing?
note that this is how I am getting my BucketAggregate:
var childAgg = response.Aggregations[ss.Type] as SingleBucketAggregate;
var nestedAgg = childAgg.Aggregations[ss.Path] as SingleBucketAggregate;
var countAgg = nestedAgg.Aggregations[ssTermsName] as BucketAggregate;
return new ProviderResult<BucketAggregate>
{
Result = countAgg,
};
Thank!
~john
additional:
ElasticClient elasticClient_BuiltInSerializer = new ElasticClient();
var source = elasticClient_BuiltInSerializer.SourceSerializer.SerializeToString(o);
var response = elasticClient_BuiltInSerializer.RequestResponseSerializer.SerializeToString(o);
ConnectionSettings connectionSettings = new ConnectionSettings(new SingleNodeConnectionPool(new Uri("http://fake")), JsonNetSerializer.Default);
ElasticClient elasticClient_JsonNetSerializer = new ElasticClient(connectionSettings);
var source2 = elasticClient_JsonNetSerializer.SourceSerializer.SerializeToString(o);
var response2 = elasticClient_JsonNetSerializer.RequestResponseSerializer.SerializeToString(o);
Are there any data types in GraphQL that can be used to describe a JSON Patch operation?
The structure of a JSON Patch operation is as follows.
{ "op": "add|replace|remove", "path": "/hello", "value": ["world"] }
Where value can be any valid JSON literal or object, such as.
"value": { "name": "michael" }
"value": "hello, world"
"value": 42
"value": ["a", "b", "c"]
op and path are always simple strings, value can be anything.
If you need to return JSON type then graphql have scalar JSON
which return any JSON type where you want to return it.
Here is schema
`
scalar JSON
type Response {
status: Boolean
message: String
data: JSON
}
type Test {
value: JSON
}
type Query {
getTest: Test
}
type Mutation {
//If you want to mutation then pass data as `JSON.stringify` or json formate
updateTest(value: JSON): Response
}
`
In resolver you can return anything in json format with key name "value"
//Query resolver
getTest: async (_, {}, { context }) => {
// return { "value": "hello, world" }
// return { "value": 42 }
// return { "value": ["a", "b", "c"] }
// return anything in json or string
return { "value": { "name": "michael" } }
},
// Mutation resolver
async updateTest(_, { value }, { }) {
// Pass data in JSON.stringify
// value : "\"hello, world\""
// value : "132456"
// value : "[\"a\", \"b\", \"c\"]"
// value : "{ \"name\": \"michael\" }"
console.log( JSON.parse(value) )
//JSON.parse return formated required data
return { status: true,
message: 'Test updated successfully!',
data: JSON.parse(value)
}
},
the only thing you need to specifically return "value" key to identify to get in query and mutation
Query
{
getTest {
value
}
}
// Which return
{
"data": {
"getTest": {
"value": {
"name": "michael"
}
}
}
}
Mutation
mutation {
updateTest(value: "{ \"name\": \"michael\" }") {
data
status
message
}
}
// Which return
{
"data": {
"updateTest": {
"data": null,
"status": true,
"message": "success"
}
}
}
I need somehow to store metadata in the can.Model
I use findAll method and receive such JSON:
{
"metadata": {
"color": "red"
},
"data": [
{ "id": 1, "description": "Do the dishes." },
{ "id": 2, "description": "Mow the lawn." },
{ "id": 3, "description": "Finish the laundry." }
]
}
I can work with data like can.Model.List, but I need metadata like a static property or something.
You can use can.Model.parseModels to adjust your response JSON before it's turned into a can.Model.List.
parseModels: function(response, xhr) {
var data = response.data;
var metadata = response.metadata;
var properties;
if(data && data.length && metadata) {
properties = Object.getOwnPropertyNames(metadata);
can.each(data, function(datum) {
can.each(properties, function(property) {
datum[property] = metadata[property];
});
});
}
return response;
}
Here's a functional example in JS Bin: http://jsbin.com/qoxuju/1/edit?js,console
I am unable to successfully return a populated instance of List<StringDictionary>> from Web API Controller to a C# console app. Here are the details...
Web API Code:
[HttpPost]
public async Task<HttpResponseMessage> Get(IEnumerable<long> ids)
{
var results = [assume populated instance of List<StringDictionary>>]
return Request.CreateResponse<List<StringDictionary>>(HttpStatusCode.OK, results);
}
I have the following client side code:
using (var httpClient = new HttpClient { BaseAddress = new Uri(baseAddress) })
{
var httpResponse = httpClient.PostAsJsonAsync<long[]>("api/promotions", mockIds).Result;
if (httpResponse.IsSuccessStatusCode)
{
var content = httpResponse.Content.ReadAsAsync<List<StringDictionary>>().Result; ***** DOES NOT WORK ****
}
}
I get the following error:
{"Cannot create and populate list type System.Collections.Specialized.StringDictionary. Path '[0]', line 1, position 2."}
What obvious fact am I missing here?
UPDATE - what's interesting is if I change StringDictionary to Dictionary it works great.
The difference is because of DeSerialization. JSON deserializer is not able to deserialize the format you are sending. If you just try to send single object you will get this error: Cannot create and populate list type System.Collections.Specialized.StringDictionary.
This link can help you getting more understanding.
Here is the JSON representation of serialized Dictionary and String dictionary.
Dictionary
[
{
"1": "A",
"4": "G"
},
{
"1": "A",
"3": "B"
}
]
String Dictionary
[
[
{
"_key": "4",
"_value": "G"
},
{
"_key": "1",
"_value": "A"
}
],
[
{
"_key": "3",
"_value": "B"
},
{
"_key": "1",
"_value": "A"
}
]
]