I am trying to parse JSON into a token object. Right now Im using JSON.Net to generate a static class, and parsing it using Json2csharp, but I would like to make each array element its own Token object and I'm not quite sure how to do that. Do I need to implement my own JSON parser? I can modify the JSON object as needed.
My JSON Deserializer: JSONopMap jo = JsonConvert.DeserializeObject<JSONopMap>(myjson2);
public class JSONopMap
{
List<List<string>>addr {get;set;}
}
JSON
{
'addr':[['~address'],['removeall','.'],['append',' ','~age']]
}
My end goal is to create a MyToken class like this:
public class MyToken
{
public enum tokenType {get;set;}
public List<string> parts {get;set;}
}
public class TokenParent{
public string ResultName{get;set;}
public List<MyToken> mytokens{get;set;}
}
public enum tokenType{Map,Append,Removeall,Lower}
So I would have three MyToken objects like this:
new MyToken{
tokenType=Map,
parts=new List<string>(){"~address"}
}
new MyToken{
tokenType=Removeall,
parts=new List<string>(){"."}
}
new MyToken{
tokenType=Append,
parts=new List<string>(){" ","~age"}
}
and a parent which contained them all:
new TokenParent{
ResultName="addr",
mytokens = (the tokens created above)
}
Related
I’ve got a very simple scenario.
I have an api response that simply returns an array of strings.
[‘test’,’test2’,’test3’]
I need to deserialise into an object to integrate with some current code.
I’ve tried using a straight class with a single property of type List but no dice.
How to deserialise into single object?
If you are using Visual Studio, you can try to use the Paste special - Paste JSON as classes under the Edit menu. Otherwise you can use this simple tool https://json2csharp.com/.
For deserialize the json string, you can use this two extension method:
using System.Runtime.Serialization.Json;
public static T DeserializeFromJsonString<T>(this string data)
{
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(data)))
return stream.DeserializeFromJsonStream<T>();
}
public static T DeserializeFromJsonStream<T>(this Stream stream)
{
T result = (T)new DataContractJsonSerializer(typeof(T)).ReadObject(stream);
return result;
}
if you need deserialise the api outPut into single object:
class _object
{
public List<string> value { get; set; }
public _object(List<string> val)=>
value = val;
}
string[] apiOutput = { "test", "test2", "test3" };
_object myobject = new _object(apiOutput.ToList());
If you want to convert the array into a list of objects:
class _object
{
public string value { get; set; }
public _object(string val)=>
value = val;
}
string[] apiOutput = {"test", "test2", "test3"};
List<_object> listObjest = apiOutput.Select(x => new _object(x)).ToList();
listObjest.ForEach(x=>Console.WriteLine(x.value));
I have a source JSON object that I get from a server that looks like this:
{
"Property A": .098
}
I have a C# class that I deserialize the JSON into using the following:
public class foo {
[JsonProperty("Property A")]
public decimal PropertyA{ get; set;}
}
var ret = JsonConvert.DeserializeObject<foo>(File.ReadAllText(someJsonString);
This allows me to read in a JSON file and convert it to a C# object. But now I would like to write this object out to JSON but change the format to be this:
{
"property_a":.098
}
I currently have another class that is identical and the only difference is that I change the JsonProperty field to the new desired name:
public class foo {
[JsonProperty("property_a")]
public decimal PropertyA{ get; set; }
}
Is there a way using Newtonsoft to have a JsonProperty read as a particular value but write as a different?
I'm working on a Unity (C#) project and trying to convert JSON data from an API to a list of dictionaries. I'm trying to use Unity's JSONSerialization, but I'm not sure what to do.
In the documentation, it says the following, and I was wondering if anyone could guide me to how I can convert the JSON? Sorry for the easy question as I'm new to C# and in the other languages I use like Javascript/Python, this is quite easily done.
Passing other types directly to the API, for example primitive types
or arrays, is not currently supported. For now you will need to wrap
such types in a class or struct of some sort.
https://docs.unity3d.com/Manual/JSONSerialization.html
The JSON returned is as follows and is a list of dictionaries, and each dictionary has two keys (_id and firstName).
[{"_id":"xxx", "firstName":"Brayann"}, {"_id":"yyy", "firstName":"Peter"}]
Create object in which you will Deserialize the json. Call ToDictionary after that.
Full example: dotNetFiddle
public static void Main(string[] args)
{
string json = #"[{ ""_id"":""xxx"", ""firstName"":""Brayann""}, { ""_id"":""yyy"", ""firstName"":""Peter""}]";
var result = JsonConvert.DeserializeObject<List<RootListObject>>(json)
.ToDictionary(x=> x.id, y=> y.firstName);
}
public class RootListObject
{
[JsonProperty(PropertyName ="_id")]
public string id { get; set; }
public string firstName { get; set; }
}
As far as I know you can't deserialize as enumarable of dictionary but you can create a class for this purpose which is more reasonable:
public class SomeDataType
{
public string _id { get; set; }
public string firstName { get; set; }
}
Then you can deserialize as List<SomeDataType>.
Even if you really require the dictionary you can add a ToDictionary method to your class.
I have a json like
{"NewMessage":[{"Id":-1,"Message":"Test","MessageName":"test1"}],"OldMessage":[]}
and I need to deserialize this json in to my class object.
My Class
public class NewMessage{
public int Id{get;set;}
public string Message{get;set;}
public string MessageName{get;set;}
}
public class OldMessage{
public int Id{get;set;}
public string Message{get;set;}
public string MessageName{get;set;}
}
how can we achive this by using newtonsoft.json. can anyone help. thanks in advance
Your JSON actually contain an object which have properties of your defined classes - given the code posted, you don't have a class to deserialize into.
The first thing you can do is obvious - create a third class - MessagePair - which declares two properties - NewMessage[] and OldMessage[]. Then you can deserialize the JSON string like this:
var theMessages = JsonConvert.DeserializeObject<MessagePair>(jsonText);
If you don't like to create separate class, you can then deserialize into anonymous object like this:
var theMessages = new {
NewMessage[] NewMessages = null,
OldMessage[] OldMessages = null
};
theMessages = JsonConvert.DeserializeAnonymousType(jsonText, theMessages);
I need my JSON output to be like the following (array of object}:
{
"values":[{"1","one"},{"2","two"},{"3","three"},{"4","four"}]
}
However, when I serialize the following C# class:
public class MyObject
{
public List<string>[] values {get;set}
}
It results in the following (array of array):
{
"values":[["1","one"],["2","two"],["3","three"],["4","four"]]
}
I've tried many variations on this object. Like the following:
public class MyObject
{
public KeyValuePair[] values {get;set}
}
Which gives me (array of KeyValuePair):
{
"values":[{"Key":"1","Value":"one"},{"Key":"2","Value":"two"},{"Key":"3","Value":"three"},{"Key":"4","Value":"four"}]
}
Is there a C# object property which would serialize to an array of json objects which do not have the object property names included?:
{
"values":[{"1","one"},{"2","two"},{"3","three"},{"4","four"}]
}
I may be answering my own question here, but here is what I found. The following will return an array of objects without property names. However, it is a hack and uses the Dictionary Key as the json property name:
public class MyObject
{
public Dictionary<string, string>[] values { get; set; }
}
Which yields the following:
{
"values":[{"1":"one"},{"2":"two"},{"3":"three"},{"4":"four"}]
}