I am getting JSON data by calling a service which format like :
[
[
{
"AgentStatus": "- Active",
"Basement": "None",
"BasementType": "",
"Baths": "4",
"BathsHalf": "1",
"Beds": "6"
},
[
"372010-1.jpg"
]
],
[
{
"AgentStatus": "- Active",
"Basement": "Finished,Full",
"BasementType": "FULL FINISHED",
"Baths": "2",
"BathsHalf": "1",
"Beds": "3"
},
[
"377388-1.jpg",
"377388-2.jpg",
"377388-12.jpg"
]
]
]
To parse this JSON i made class like :
public class RetsProperty
{
public PropertyAttributes PropAttributes { get; set; }
public string[] ImgUrls { get; set; }
}
public class PropertyAttributes
{
public string AgentStatus { get; set; }
public string Basement { get; set; }
public string BasementType { get; set; }
public string Baths { get; set; }
public string BathsHalf { get; set; }
public string Beds { get; set; }
}
And i have used Newtonsoft Json to deserialize JSON data
var retsPropertyItems = Newtonsoft.Json.JsonConvert.DeserializeObject<List<RetsProperty>>(propertyJsonString);
But it can't parse it returns below error :
I think it is because i can't able to create class properly.
So how can i format my class ?
Or is it possible to map the way i did ?
Thanks
You have really bad formatted JSON becouse it have array within array without property name. So you just should parse it carefully.
I came up with a solution that could be not so bad and easy to understand (If i understand your JSON format right). The idea is to wrap your JSON with property name and then parse his constuction.
You should wrap your JSON same way:
var wrappedText = #"{ ""Prop"": " + propertyJsonString + " }";
And then you can parse in with Newtonsoft Json:
var jsonData = JObject.Parse(wrappedText);
Now you have your JSON data and you should parse it manualy. I recommend you this way:
List<RetsProperty> RetsProperties = new List<RetsProperty>();
foreach (var prop in jsonData["Prop"])
{
RetsProperties.Add(new RetsProperty
{
ImgUrls = Newtonsoft.Json.JsonConvert.DeserializeObject<string[]>(prop.Last.ToString()),
PropAttributes = Newtonsoft.Json.JsonConvert.DeserializeObject<PropertyAttributes>(prop.First.ToString())
});
};
You should understand that it will work only if you have 2 array items in last array. Take a look at prop.First and prop.Last.
First of all you have a very strange JSON, but as you said you receive it from external service. You can parse such JSON using JArray and LINQ, but of course this method is very dependent on the structure of JSON.
var retsProperties = JArray.Parse(json)
.Select(item => new RetsProperty
{
PropAttributes = item.First.ToObject<PropertyAttributes>(),
ImgUrls = item.Last.ToObject<string[]>()
})
.ToList();
Related
I have the following JSON string
{ "Params": [ { "name": "id","value": "1234567" },
{ "name": "class","value": "six"}
],
"type":"general"}
and equivalent class as below
public class class1
{
public Param[] Params { get; set; }
public string Type { get; set; }
}
public class Param
{
public string Name { get; set; }
public string Value { get; set; }
}
How can I search if there is an object with name as id in Params array and how to fetch its value?
Include Newtonsoft.Json
using Newtonsoft.Json;
Then deserialize your json string to an object of class1, then search using linq.
string json = "{\"Params\": [ { \"name\": \"id\",\"value\": \"1234567\" },{ \"name\": \"class\",\"value\": \"six\"}],\"type\":\"general\"}";
// convert to object
var jsonObject = JsonConvert.DeserializeObject<class1>(json);
// filter
var result = jsonObject.Params.Where(p=> p.Name == "id" && p.Value == "1234567");
The Json.net documentation has a pretty good example you can use as well. It shows a way to do without necessarily converting to a C# object. See below
https://www.newtonsoft.com/json/help/html/queryinglinqtojson.htm
I have JSON string that came from AWS Lambda:
"body": "{'From': nemesises#live.com, 'To': suhomlin.eugene93#gmail.com}",
And try to deserialize it like this
var email = JsonConvert.DeserializeObject<SendEmailMessage>(emailRequest.Message);
Here is the class to what I need to deserialize
public class SendEmailMessage
{
public string From { get; set; }
public string To { get; set; }
public object Data { get; set; }
public int TemplateId { get; set; }
public List<string> Attachments { get; set; }
}
But I get this error
Newtonsoft.Json.JsonReaderException: Unexpected content while parsing JSON. Path 'From', line 1, position 11.
How I can solve this?
You need to wrap the entire json in {}.
{
"body": "{'From': nemesises#live.com, 'To': suhomlin.eugene93#gmail.com}"
}
You can use a site like https://jsonlint.com/ to work out things like this.
So the problem was in the format of the body
Here the correct format is
{
"Records": [
{
"messageId": "19dd0b57-b21e-4ac1-bd88-01bbb068cb78",
"receiptHandle": "MessageReceiptHandle",
"body": "{ \"Message\":\"{ 'from': 'nemesises#live.com','to': 'suhomlin.eugene93#gmail.com',}\"}",
"attributes": {
"ApproximateReceiveCount": "1",
"SentTimestamp": "1523232000000",
"SenderId": "123456789012",
"ApproximateFirstReceiveTimestamp": "1523232000001"
},
"messageAttributes": {},
"md5OfBody": "7b270e59b47ff90a553787216d55d91d",
"eventSource": "aws:sqs",
"eventSourceARN": "arn:{partition}:sqs:{region}:123456789012:MyQueue",
"awsRegion": "{region}"
}
]
}
JSON
{
"count": 3,
"value": [
{
"id": "AAAAAAAAAAAAA",
"description": "test1",
"name": "name1"
},
{
"id": "BBBBBBBBBB",
"description": "test2",
"name": "name2"
},
{
"id": "CCCCCCCCCCCC",
"description": "test3",
"name": "name3"
}
]
}
I have a code in my solution retrieving from a LIST api and giving the JSON above.
How can I use a LINQ to retrieve specific values? (e.g) I need to select name1 and I will get the id,description,name values.
I am using a dynamic variable in my code:
dynamic json = JObject.Parse(client.GetString().Result);
I'd been tinkering with other online guides the past few hours. However, can't get the result right.
Please help.
One solution would be to deserialize your JSON string into C# objects and then use Linq to get a specific object.
C# class definitions:
public class Content
{
[JsonProperty("count")]
public int Count { get; set; }
[JsonProperty("value")]
public List<Value> Values { get; set; }
public Content()
{
Values = new List<Value>();
}
}
public class Value
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
}
Deserializing and getting the object:
string json = #"{
""count"": 3,
""value"": [
{
""id"": ""AAAAAAAAAAAAA"",
""description"": ""test1"",
""name"": ""name1""
},
{
""id"": ""BBBBBBBBBB"",
""description"": ""test2"",
""name"": ""name2""
},
{
""id"": ""CCCCCCCCCCCC"",
""description"": ""test3"",
""name"": ""name3""
}
]
}";
Content content = JsonConvert.DeserializeObject<Content>(json);
Value value = content.Values.FirstOrDefault(x => x.Name.Equals("name1", StringComparison.InvariantCultureIgnoreCase));
First, you can create a class to represent a client:
public class Client
{
public string Id { get; set; }
public string Description { get; set; }
public string Name { get; set; }
}
With this class, you can use JObject.Parse (as you're already doing) to parse the JSON into something that can be queried, use SelectToken to pull out the value array and then use ToObject to convert that to a list of Clients. Here's what that looks like:
var jsonObject = JObject.Parse(json_source);
var jsonObjectValue = jsonObject.SelectToken("value");
var clients = jsonObjectValue.ToObject<List<Client>>();
Once you've got your clients variable, you can use a simple LINQ statement to find the one that is name1:
var clientWithName1 = clients.SingleOrDefault(x => x.Name == "name1");
In this case, clientWithName will be null if no such client was found.
Here's a dotnetfiddle that demonstrates a complete solution.
Create an object Client that has properties id, description and name. Deserialize the json into a list of these objects.
List<Client> clients = JsonConvert.Deserialize<List<Client>>(json_source);
string desc = clients[0].description;
Apparently with fiddling with my code I found an answer for myself.
Thanks for to the ones trying to help me for giving me ideas.
var requestWorkProcess = await client.GetStringAsync("my url");
var workProcessId = JObject.Parse(requestWorkProcess)["value"].Children<JObject>().FirstOrDefault(o => o["name"].ToString() == workProcess).GetValue("id");
I am getting this JSON response from a system I am connecting to and trying to figure out the best way to deserialize it into a C# object. I am currently using RestSharp which seems pretty straight forward to use but the format of the JSON is baffling me a bit. Here is the format that its coming in as:
[
{"name": "Tickets:",
"schema": [
{"dataType": "string", "colName": "First", "idx": 0},
{"dataType": "string", "colName": "Second", "idx": 1},
{"dataType": "string", "colName": "Name", "idx": 2}
],
"data": [
["bill", "test", "joe"],
["bill2", "test2", "joe2"],
["bill3", "test3", "joe3"]
]
}
]
Here is my current code:
var url = "http://myUrl:10111";
var client = new RestClient { BaseUrl = url };
var request = new RestRequest { Method = Method.GET, Resource = "/search?fmt=Json", RequestFormat = DataFormat.Json };
request.AddHeader("accept", "application/json");
var response = client.Execute(request);
var wptResponse = new JsonDeserializer().Deserialize<TicketResults>(response);
return wptResponse;
but as stated above I am trying to figure out the correct way to model the TicketResults object to support deserializing this message above.
Ideally I would like something like this:
public class TicketResults
{
public List<Ticket> Tickets {get;set;}
}
public class Ticket
{
public string First {get;set;}
public string Second {get;set;}
public string Name {get;set;}
}
and in this example above would get three entries in the Tickets collection.
Also, is the above JSON format normal as i have never seen this broken out into separate schema and data section (I can see where it might save some space but in this case the messages are not that big)
In Visual Studio 2012 and up and you can go to Edit > Paste Special > Paste JSON as classes. It produces the following code given your example pasted from clipboard.
public class Rootobject
{
public Class1[] Property1 { get; set; }
}
public class Class1
{
public string name { get; set; }
public Schema[] schema { get; set; }
public string[][] data { get; set; }
}
public class Schema
{
public string dataType { get; set; }
public string colName { get; set; }
public int idx { get; set; }
}
string json = File.ReadAllText("json.txt");
Rootobject root = new Rootobject();
root.Property1 = JsonConvert.DeserializeObject<Class1[]>(json);
I agree the json format is quite ... goofy. Here's how to model your dto:
public class JsonDto
{
public string name { get; set; }
public Schema[] schema {get; set;}
public string[][] data { get; set; }
}
public class Schema
{
public string dataType { get; set; }
public string colName { get; set; }
public int idx { get; set; }
}
I was able to get your string (unaltered) to deserialize with JSON.Net like this:
var jsonDto = JsonConvert.DeserializeObject<JsonDto[]>(json);
Let me know if you're still having trouble.
Do you have any control over the structure of the JSON being returned? It's kind of wacky. For some reason the field names and the data is separated out. If the format was a little more sensible like:
[
{
"First": "bill",
"Second": "test",
"Name": "joe"
},
{
"First": "bill2",
"Second": "test2",
"Name": "joe2"
},
]
Then you would have a shot at serializing it to your Ticket class. However, without reworking the JSON structure, which I don't recommend you do, the C# class that you are serializing to will have to match the JSON structure.
I suppose you could come up with an intermediary class to hold the JSON data as it comes to you. Then you could loop over those objets and create instances of the Ticket class out of them. At least that way you end up with a data structure you can work with.
I have Json string like below
{
"JsonValues":{
"id": "MyID",
"values": {
"value1":{
"id": "100",
"diaplayName": "MyValue1"
},
"value2":{
"id": "200",
"diaplayName": "MyValue2"
}
}
}
}
I want to convert Json string to below classes
class ValueSet
{
[JsonProperty("id")]
public string id
{
get;
set;
}
[JsonProperty("values")]
public List<Value> values
{
get;
set;
}
}
class Value
{
public string id
{
get;
set;
}
public string DiaplayName
{
get;
set;
}
}
My deserialization code is
JavaScriptSerializer js = new JavaScriptSerializer();
StreamReader sr = new StreamReader(#"ValueSetJsonString.txt");
string jsonString = sr.ReadToEnd();
var items = JsonConvert.DeserializeObject<ValueSet>(jsonString);
But I am getting null values after serialization, How i can solve this?
As others have already pointed out, the reason you are not getting the results you expect is because your JSON does not match the class structure that you are trying to deserialize into. You either need to change your JSON or change your classes. Since others have already shown how to change the JSON, I will take the opposite approach here.
To match the JSON you posted in your question, your classes should be defined like those below. Notice I've made the following changes:
I added a Wrapper class corresponding to the outer object in your JSON.
I changed the Values property of the ValueSet class from a List<Value> to a Dictionary<string, Value> since the values property in your JSON contains an object, not an array.
I added some additional [JsonProperty] attributes to match the property names in your JSON objects.
Class definitions:
class Wrapper
{
[JsonProperty("JsonValues")]
public ValueSet ValueSet { get; set; }
}
class ValueSet
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("values")]
public Dictionary<string, Value> Values { get; set; }
}
class Value
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("diaplayName")]
public string DisplayName { get; set; }
}
You need to deserialize into the Wrapper class, not the ValueSet class. You can then get the ValueSet from the Wrapper.
var valueSet = JsonConvert.DeserializeObject<Wrapper>(jsonString).ValueSet;
Here is a working program to demonstrate:
class Program
{
static void Main(string[] args)
{
string jsonString = #"
{
""JsonValues"": {
""id"": ""MyID"",
""values"": {
""value1"": {
""id"": ""100"",
""diaplayName"": ""MyValue1""
},
""value2"": {
""id"": ""200"",
""diaplayName"": ""MyValue2""
}
}
}
}";
var valueSet = JsonConvert.DeserializeObject<Wrapper>(jsonString).ValueSet;
Console.WriteLine("id: " + valueSet.Id);
foreach (KeyValuePair<string, Value> kvp in valueSet.Values)
{
Console.WriteLine(kvp.Key + " id: " + kvp.Value.Id);
Console.WriteLine(kvp.Key + " name: " + kvp.Value.DisplayName);
}
}
}
And here is the output:
id: MyID
value1 id: 100
value1 name: MyValue1
value2 id: 200
value2 name: MyValue2
http://json2csharp.com/
I found the above link incredibly helpful as it corrected my C# classes by generating them from the JSON that was actually returned.
Then I called :
JsonConvert.DeserializeObject<RootObject>(jsonString);
and everything worked as expected.
Did you check this line works perfectly & your string have value in it ?
string jsonString = sr.ReadToEnd();
if yes, try this code for last line:
ValueSet items = JsonConvert.DeserializeObject<ValueSet>(jsonString);
or if you have an array of json you can use list like this :
List<ValueSet> items = JsonConvert.DeserializeObject<List<ValueSet>>(jsonString);
good luck
Your data structure and your JSON do not match.
Your JSON is this:
{
"JsonValues":{
"id": "MyID",
...
}
}
But the data structure you try to serialize it to is this:
class ValueSet
{
[JsonProperty("id")]
public string id
{
get;
set;
}
...
}
You are skipping a step: Your JSON is a class that has one property named JsonValues, which has an object of your ValueSet data structure as value.
Also inside your class your JSON is this:
"values": { ... }
Your data structure is this:
[JsonProperty("values")]
public List<Value> values
{
get;
set;
}
Note that { .. } in JSON defines an object, where as [ .. ] defines an array. So according to your JSON you don't have a bunch of values, but you have one values object with the properties value1 and value2 of type Value.
Since the deserializer expects an array but gets an object instead, it does the least non-destructive (Exception) thing it could do: skip the value. Your property values remains with it's default value: null.
If you can: Adjust your JSON. The following would match your data structure and is most likely what you actually want:
{
"id": "MyID",
"values": [
{
"id": "100",
"diaplayName": "MyValue1"
}, {
"id": "200",
"diaplayName": "MyValue2"
}
]
}
Json Convert To C# Class = https://json2csharp.com/json-to-csharp
after the schema comes out
WebClient client = new WebClient();
client.Encoding = Encoding.UTF8;
string myJSON = client.DownloadString("http://xxx/xx/xx.json");
var valueSet = JsonConvert.DeserializeObject<Root>(myJSON);
The biggest one of our mistakes is that we can't match the class structure with json.
This connection will do the process automatically. You will code it later ;) = https://json2csharp.com/json-to-csharp
that's it.
you have an unmatched jSon string, if you want to convert into a list, try this
{
"id": "MyID",
"values": [
{
"id": "100",
"diaplayName": "MyValue1",
},
{
"id": "200",
"diaplayName": "MyValue2",
}
]
}
This is possible too:
using System.Web.Helpers;
var listOfObjectsResult = Json.Decode<List<DataType>>(JsonData);
This takes the JsonElement and deserializes it to List of objects.
List<object> draftInvoices = JsonConvert.DeserializeObject<List<object>>(jsonDrafts.ToString());
Example:
[HttpPost]
[Route("CreateDraft")]
public async Task<IActionResult> CreateDraft([FromBody] JsonElement jsonDrafts)
{
List<object> draftInvoices = JsonConvert.DeserializeObject<List<object>>(jsonDrafts.ToString());
for (int i = 0; i < draftInvoices.Count; i++)
{
........
}
You may use Json.Net framework to do this.
Just like this :
Account account = JsonConvert.DeserializeObject<Account>(json);
the home page : http://json.codeplex.com/
the document about this : http://james.newtonking.com/json/help/index.html#