I want to create multi level Json, Using http://json2csharp.com/. I created classes. But not sure how to use it.
public class MassPay
{
public string legal_name { get; set; }
public string account_number { get; set; }
public string routing_number { get; set; }
public string amount { get; set; }
public string trans_type { get; set; }
public string account_class { get; set; }
public string account_type { get; set; }
public string status_url { get; set; }
public string supp_id { get; set; }
public string user_info { get; set; }
}
public class MassPayList
{
public string oauth_consumer_key { get; set; }
public string bank_id { get; set; }
public string facilitator_fee { get; set; }
public IList<MassPay> mass_pays { get; set; }
}
These are my classes and this is Json Format i want to create...
there are extra elements...
{
"oauth_consumer_key":"some_oauth_token",
"mass_pays":[
{"legal_name":"SomePerson1",
"account_number":"888888888",
"routing_number":"222222222",
"amount":"10.33",
"trans_type":"0",
"account_class":"1",
"account_type":"2"
},
{"legal_name":"SomePerson2",
"account_number":"888888888",
"routing_number":"222222222",
"amount":"10.33",
"trans_type":"0",
"account_class":"1",
"account_type":"1"}
]
}
So far i have come up with below code..I am using JObject, and all others wer single level so it was pretty easy. but when it comes to two or three level its difficult.
public JObject AddMassPayRequest(MassPayList lMassPayList, MassPay lMassPay)
{
JObject pin = new JObject(
new JProperty("legal_name", lMassPay.legal_name),
new JProperty("account_number", lMassPay.account_number),
new JProperty("routing_number", lMassPay.routing_number),
new JProperty("amount", lMassPay.amount),
new JProperty("trans_type", lMassPay.trans_type),
new JProperty("account_class", lMassPay.account_class),
new JProperty("account_type", lMassPay.account_type),
new JProperty("status_url", lMassPay.status_url),
new JProperty("supp_id", lMassPay.supp_id),
new JProperty("status_url", lMassPay.status_url),
new JProperty("user_info", lMassPay.user_info)
);
return pin;
}
public JObject AddMassPayRequestList(MassPayList lMassPayList, MassPay lMassPay)
{
JObject pin = new JObject(
new JProperty("mass_pays", lMassPayList.mass_pays),
new JProperty("bank_id", lMassPayList.bank_id),
new JProperty("facilitator_fee", lMassPayList.facilitator_fee),
new JProperty("oauth_consumer_key", lMassPayList.oauth_consumer_key)
);
return pin;
}
Can some one help me how to do this..?
if you're using ASP.NET MVC you just need to use the Json response action using your existing classes.
You could simply do something like this in a controller:
return Json(new { PoId = newPoId, Success = true });
or an actual concrete model class:
var _AddMassPayRequestList = new AddMassPayRequestList();
...
returning a populated instance of your AddMassPayRequestList class:
return Json(_AddMassPayRequestList);
So finally I got this answer, Its simple structure. Using this u can create any type of Json... It doesnt have to follow same structure..
The logic behind this is add things you want at start, create class and inside that properties you want to add into json. SO while passign just add for loop and pass Object to the list.. It will loop through and create JSon for You..
If you have any doubts, let me know happy to help you
public String ToJSONRepresentation(List<MassPay> lMassPay)
{
StringBuilder sb = new StringBuilder();
JsonWriter jw = new JsonTextWriter(new StringWriter(sb));
jw.Formatting = Formatting.Indented;
jw.WriteStartObject();
jw.WritePropertyName("oauth_consumer_key");
jw.WriteValue("asdasdsadasdas");
jw.WritePropertyName("mass_pays");
jw.WriteStartArray();
int i;
i = 0;
for (i = 0; i < lMassPay.Count; i++)
{
jw.WriteStartObject();
jw.WritePropertyName("legal_name");
jw.WriteValue(lMassPay[i].legal_name);
jw.WritePropertyName("account_number");
jw.WriteValue(lMassPay[i].account_number);
jw.WritePropertyName("routing_number");
jw.WriteValue(lMassPay[i].routing_number);
jw.WritePropertyName("amount");
jw.WriteValue(lMassPay[i].amount);
jw.WritePropertyName("trans_type");
jw.WriteValue(lMassPay[i].trans_type);
jw.WritePropertyName("account_class");
jw.WriteValue(lMassPay[i].account_class);
jw.WritePropertyName("account_type");
jw.WriteValue(lMassPay[i].account_type);
jw.WritePropertyName("status_url");
jw.WriteValue(lMassPay[i].status_url);
jw.WritePropertyName("supp_id");
jw.WriteValue(lMassPay[i].supp_id);
jw.WriteEndObject();
}
jw.WriteEndArray();
jw.WriteEndObject();
return sb.ToString();
}
Related
I am building an API pulling data from Azure SQL would like to create a JSON array.
Currently I have an Azure Function written in C#.
Sample data looks like this:
I would like the output to look like this
My Azure Function is working fine, I just need to create an array. (I think)
await connection.OpenAsync();
SqlDataReader dataReader = await command.ExecuteReaderAsync();
var r = Serialize(dataReader);
json = JsonConvert.SerializeObject(r, Formatting.Indented);
I'm new to .NET and not sure quite where to begin. Thanks!
You could do it this way. Read the data into a Type that you can then use LINQ on to group into the desired shape, then serialize to JSON.
//Start with a list of the raw data by reading the rows into CardData list
List<CardData> cards = new List<CardData>();
while (dataReader.Read())
{
//You should check for DBNull, this example not doing that
cards.Add(new CardData
{
card_key = dataReader.GetString(0),
card_name = dataReader.GetString(1),
card_network = dataReader.GetString(2),
annual_fee = dataReader.GetDecimal(3),
speed_bonus_category = dataReader.GetString(4),
speed_bonus_amount = dataReader.GetInt32(5)
});
}
//Now transform the data into an object graph that will serialize
//to json the way you want. (flattens the redundant data)
var grp = cards.GroupBy(x => new { x.card_key, x.card_name, x.card_network, x.annual_fee });
var groupedData = new List<CardsModel>();
groupedData = grp.Select(g => new CardsModel
{
card_key = g.Key.card_key,
card_name = g.Key.card_name,
card_network = g.Key.card_network,
annual_fee = g.Key.annual_fee,
Bonuses = g.Select(b => new SpeedBonus
{
SpeedBonusCategory = b.speed_bonus_category,
SpeedBonusAmount = b.speed_bonus_amount
}).ToList()
}).ToList();
//Finally you can serialize
var json = JsonConvert.SerializeObject(groupedData, Formatting.Indented);
Here are the supporting classes you could use:
//represents the non-redundant object graph
public class CardsModel
{
public string card_key { get; set; }
public string card_name { get; set; }
public string card_network { get; set; }
public decimal annual_fee { get; set; }
public List<SpeedBonus> Bonuses { get; set; }
}
public class SpeedBonus
{
public string SpeedBonusCategory { get; set; }
public int SpeedBonusAmount { get; set; }
}
//represents raw data, has redundant cc info
public class CardData
{
public string card_key { get; set; }
public string card_name { get; set; }
public string card_network { get; set; }
public decimal annual_fee { get; set; }
public string speed_bonus_category { get; set; }
public int speed_bonus_amount { get; set; }
}
i want add list data (from class) to sub class list for sent JSON FORMAT to other api.
Class
public class InPaymentDetailResponse
{
public List<InPaymentDetail> Data { get; set; }
}
public class InPaymentDetail
{
public string runningno { get; set; }
public decimal totalpremium { get; set; }
}
public class InformationRequest
{
.....
.....
public List<CreateDetailRequest> _detailData { get; set; }
public ExPaymentRequest _payment { get; set; }
}
public class ExPaymentRequest
{
.....
.....
public ExCashtransaction _cash { get; set; }
}
public class ExCashtransaction
{
public string createby { get; set; }
public DateTime createdate { get; set; }
public List<ExCashtransactionDetailsRequest> details { get; set; }
}
public class ExCashtransactionDetailsRequest
{
public string runningno { get; set; }
public decimal amount { get; set; }
}
Code C#
private async Task<.....> CreateInfo(InformationRequest r)
{
InPaymentDetailResponse resPaymentDetail = new InPaymentDetailResponse();
resPaymentDetail.Data = new List<InPaymentDetail>();
foreach (var item in r._detailData)
{
.....
..... //Process Data
.....
var resPaymentDetailData = new InPaymentDetail
{
//Add List Data To New Object
runningno = item.runningno,
totalpremium = item.totalpremium
};
resPaymentDetail.Data.Add(resPaymentDetailData);
}
HttpResponseMessage response = new HttpResponseMessage();
foreach (var res in resPaymentDetail.Data.ToList())
{
//i want add
//req._payment._cash.details.runningno = res.runningno //Ex. 10
//req._payment._cash.details.amount = res.amount //Ex. 99.9
//next loop
//req._payment._cash.details.runningno = res.runningno //Ex. 20
//req._payment._cash.details.amount = res.amount //Ex. 23.2
}
//sent to other api
response = await client.PostAsJsonAsync("", req._payment._cash);
.....
.....
}
i want result code when add list data to req._payment._cash:
(because to use it next process)
"createby": "system",
"createdate": 26/09/2018",
"details": [
{
"runningno": "10", //before add data to list is null
"amount": 99.9 //before add data to list is null
},
{
"runningno": "20", //before add data to list is null
"amount": 23.2 //before add data to list is null
}
]
Help me please. Thanks in advance.
List<ExCashtransactionDetailsRequest> detailsObj = new List<ExCashtransactionDetailsRequest>();
foreach (var res in resPaymentDetail.Data.ToList())
{
detailsObj.Add(new ExCashtransactionDetailsRequest(){ runningno =res.runningno, amount = res.amount });
}
and finally, add details object to your property
req._payment._cash.details = detailsObj;
Hi all I am trying to build a quiz application using angular JS, I am having two tables Questions and Answers and the code is as follows
public class Question
{
public int QuestionID { get; set; }
public string QuestionName { get; set; }
public List<Options> Options = new List<Options>();
}
public class Options
{
public int AnswerId { get; set; }
public int QuestionID { get; set; }
public string Answer { get; set; }
public bool isAnswer { get; set; }
}
public static class QuizDetails
{
public static string GetQuiz()
{
Dictionary<int, List<Question>> displayQuestion = new Dictionary<int, List<Question>>();
//List<Quiz> quiz = new List<Quiz>();
//Options op1 = new Options();
dbDataContext db = new dbDataContext();
var v = (from op in db.QUESTIONs
join pg in db.ANSWERs on op.QUESTION_ID equals pg.QUESTION_ID
select new { Id = op.QUESTION_ID, Name = op.QUESTION_NAME, pg.ANSWER_ID, pg.QUESTION_ID, pg.ANSWER_DESCRIPTION, pg.CORRECT_ANSWER }).ToList();
return JsonConvert.SerializeObject(v);
}
}
This is my reference code for building the application
http://www.codeproject.com/Articles/860024/Quiz-Application-in-AngularJs, how can I return the JSON format as per the code written in the JS files can some one help me
Right now GetQuiz returns a string that represents an object. Your client doesn't really know what the string contains, it just handles it as a normal string.
You can either return it in another way, for example:
return new HttpResponseMessage
{
Content = new StringContent(
JsonConvert.SerializeObject(v),
System.Text.Encoding.UTF8,
"application/json")
};
If you want to keep returning it as a string you will have to manually deserialize it in the client:
var object = angular.fromJson(returnedData);
So I have the json below that I want to Deseralize into Classes so I can work with it. But the issues is that the top two fields are a different type to all the rest
"items": {
"averageItemLevel": 718,
"averageItemLevelEquipped": 716,
"head": { ... },
"chest": { ... },
"feet": { ... },
"hands": { ... }
}
Where ... is a the Item class below, but the problem is that 2 of the fields are ints and the rest are Item, there are about 20 fields in total. So what I'd like to do is put them into a Dictionary<string, Item> but the 2 int fields are preventing me from Deseralizing it into that. I'm using JavaScriptSerializer.Deserialize<T>() to do this.
I could have each item as it's own class with the name of the item as the name of the class, but I find that to be very bad, repeating so much each time, also very hard to work with later since I cant iterate over the fields, where as I could a Dictionary. Any idea how I could overcome this?
public class Item
{
public ItemDetails itemDetails { get; set; }
public int id { get; set; }
public string name { get; set; }
public string icon { get; set; }
public int quality { get; set; }
public int itemLevel { get; set; }
public TooltipParams tooltipParams { get; set; }
public List<Stat> stats { get; set; }
public int armor { get; set; }
public string context { get; set; }
public List<int> bonusLists { get; set; }
}
Update: from the comments I came up with this solution
JObject jsonObject = JObject.Parse(json);
jsonObject["averageItemLevel"] = int.Parse(jsonObject["items"]["averageItemLevel"].ToString());
jsonObject["averageItemLevelEquipped"] = int.Parse(jsonObject["items"]["averageItemLevelEquipped"].ToString());
jsonObject["items"]["averageItemLevel"].Parent.Remove();
jsonObject["items"]["averageItemLevelEquipped"].Parent.Remove();
var finalJson = jsonObject.ToString(Newtonsoft.Json.Formatting.None);
var character = _serializer.Deserialize<Character>(finalJson);
character.progression.raids.RemoveAll(x => x.name != "My House");
return character
If I add these two classes to match your JSON I can serialize and deserialize the objects:
public class root
{
public Items items { get; set; }
}
public class Items
{
public int averageItemLevel { get; set; }
public int averageItemLevelEquipped { get; set; }
public Item head {get;set;}
public Item chest {get;set;}
public Item feet {get;set;}
public Item hands {get;set;}
}
Test rig with the WCF Serializer:
var obj = new root();
obj.items = new Items
{
averageItemLevel = 42,
feet = new Item { armor = 4242 },
chest = new Item { name = "super chest" }
};
var ser = new DataContractJsonSerializer(typeof(root));
using (var ms = new MemoryStream())
{
ser.WriteObject(ms, obj);
Console.WriteLine(Encoding.UTF8.GetString(ms.ToArray()));
Console.WriteLine("and deserialize");
ms.Position = 0;
var deserializeObject = (root) ser.ReadObject(ms);
Console.WriteLine(deserializeObject.items.feet.armor);
}
And with the JavaScriptSerializer:
var jsser = new JavaScriptSerializer();
var json = jsser.Serialize(obj);
Console.WriteLine(json);
Console.WriteLine("and deserialize");
var djson = jsser.Deserialize<root>(json);
Console.WriteLine(djson.items.feet.armor);
Both serializers give the same result for your given JSON.
I'm working with JSON (using json.net) and a C# console application and I am trying to set some values for a JSON POST to a server.
I can set some of the values, but accessing others is giving me fits.
My JSON looks like this:
{
"params" : [
{
"url" : "sys/login/user",
"data" : [
{
"passwd" : "pwd",
"user" : "user"
}
]
}
],
"session" : 1,
"id" : 1,
"method" : "exec"
}
I ran that through json2csharp and it generated me the following classes.
public class Datum
{
public string passwd { get; set; }
public string user { get; set; }
}
public class Param
{
public string url { get; set; }
public List<Datum> data { get; set; }
}
public class RootObject
{
public List<Param> #params { get; set; }
public string session { get; set; }
public int id { get; set; }
public string method { get; set; }
}
I then created this object for testing in my Main method
RootObject temp = new RootObject()
temp.id = 1;
temp.method = "exec";
temp.session = "1";
and those parameters get set just fine.
I can also set the URL param using the following:
temp.#params.Add(new Param { url = "some/url", });
It is setting the public List<Datum> data { get; set; } item that is the problem. I cannot figure out how to access that and set the user and password items.
If I add this to the Param class I can set the values, but this seems to be the wrong way/place to me.
public Param()
{
data = new List<Datum>();
data.Add(new Datum { user = "user", passwd = "pass" });
}
Well, you create your RootObject like this:
RootObject temp = new RootObject()
temp.id = 1;
temp.method = "exec";
temp.session = "1";
Then you create the params list and fill it with one Param:
temp.#params = new List<Param>();
temp.#params.Add(new Param { url = "some/url" });
You can then set the data for one param in the list (in this example the first one):
temp.#params[0].data = new List<Datum>();
temp.#params[0].data.Add(new Datum { user = "user", passwd = "pass" });
This is necessary, because #params is a list of Param objects. You could also fill the data when creating the Param instance before adding it to the list (easier, because you otherwise need to know the list index).
temp.#params = new List<Param>();
Param p = new Param { url = "some/url" };
p.data = new List<Datum>();
p.data.Add(new Datum() { ... });
temp.#params.Add(p);
Usually you'd change change the default constructors to initialize the lists already and prevent the list instances from being replaced by changing the properties to read-only, but that might not work well with JSON deserialization, so you really need to try this. It would look like this:
public class Param
{
public Param()
{
data = new List<Datum>();
}
public string url { get; set; }
public List<Datum> data { get; private set; }
}
public class RootObject
{
public RootObject()
{
#params = new List<Param>();
}
public List<Param> #params { get; private set; }
public string session { get; set; }
public int id { get; set; }
public string method { get; set; }
}