Json array column order - arrays

i have the following json:
{
"Header": {
"MCC": "415",
"FO": "0",
"REGID": "5"
},
"Contacts": [
{
"NAME": "jocelyne",
"MO": "70123456"
},
{
"NAME": "eliane",
"MO": "03123456"
}
] }
and i'm parsing the json string into a datatable using this method:
object classes:
Public Class Data
Public Header As Header
Public Contacts As DataTable
End Class
<System.Runtime.Serialization.DataContract()>
Public Class Header
<System.Runtime.Serialization.DataMember(Name:="MCC")>
Public MCC As Integer
<System.Runtime.Serialization.DataMember(Name:="FO")>
Public FO As Integer
<System.Runtime.Serialization.DataMember(Name:="REGID")>
Public RegId As Integer
End Class
.net functions:
Dim data As New Data
data = JsonConvert.DeserializeObject(Of Data)(json)
mcc = data.Header.MCC
FO = data.Header.FO
regid = data.Header.RegId
contactsDT = data.Contacts
my problem is that the contacts array in the json is being parsed as a datatable in the same order as passed in the json... is there a way to change the order of the columns? what i mean is that if i got in the json let's say mo before name i need to get in the datatable name before mo all the time
is there a way to do that?

Related

Convert JSON array objects to .net Classes

I am having issues with the below JSON String on converting it to .net class. The class that I have created so far is below as well. The particular section that I cannot get to work is group_access and roles tags. I know these are an array of objects but when I try to convert the objects i get the following error; Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Array' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
I also tried using visual studio tool (Edit>Paste Special > JSON) and jscon2csharp.com it errors out on converting the roles and group_access tags.
JSON data:
{
id: 122404,
email: 'mike#email.com',
fname: 'Mike',
lname: 'Doe',
full_name: 'Mike Doe',
resource_id: '001002',
title: '',
last_login: '2016-11-01 09:15:23',
tags: [
'Math Department', 'New Teachers'
],
grades: [
4, 5, 6
],
targets: [
'Option 1: 3 Informal Obs.'
],
caseload_tags: [],
group_access: [
10: 2
25527: 1
25645: 1
25653: 4
],
roles: [
10: [
2015: 2,
2016: 2
],
25527: [
2015: 2,
2016: 1
]
25645: [
2015: 1,
2016: 1
]
25653: [
2015: 3,
2016: 4
]
]
}
My code:
Public Class Item
Public Property id As Integer
Public Property email As String
Public Property fname As String
Public Property lname As String
Public Property full_name As String
Public Property resource_id As String
Public Property title As String
Public Property tags As IList(Of String)
Public Property grades As IList(Of String)
Public Property targets As IList(Of String)
Public Property group_access As Array
Public Property roles As Array
End Class
Public Class RootObject
Public Property type As String
Public Property limit As Integer
Public Property offset As Integer
Public Property total As Integer
Public Property time As String
Public Property items As List(Of Item)
Public Property items_count As Integer
End Class
The JSON is not valid - array elements must be separated with commata.

deserialize json file data in mvc

I have one json file in my local path sendmail.json it contains data like this
{
"from": {
"datatype": "String",
"required": false
},
"subject": {
"datatype": "String",
"required": false
},
"text": {
"datatype": "String",
"required": false
},
"to": {
"datatype": "String",
"required": false
}
}
i want to deserialize this data in mvc and i want to pass this data to .js angular controller please provide the way how to do it.
If you want to deserialize JSON and sent it to the client side, you can do it like this.
[HttpGet]
public ActionResult mailData()
{
List<test> myDeserializedObjList = (List<test>)Newtonsoft.Json.JsonConvert.DeserializeObject(Request["jsonString"], typeof(List<test>));
return Json(jsonString, JsonRequestBehavior.AllowGet);
}
Hope it works for you..!
There is no need to deserialize the JSON into an object and then serialize the object into JSON to send it to the browser.
Why not send directly the JSON file to the browser?
public class MailController : Controller
{
// GET: Mail
public ActionResult Schema()
{
return File(this.Server.MapPath("~/App_Data/sendmail.json"), "application/json");
}
}
EDIT:
Anyway here you have what you asked for:
public class MailController : Controller
{
// GET: Mail
public ActionResult Schema()
{
using (var reader = new StreamReader(this.Server.MapPath("~/App_Data/sendmail.json")))
{
var json = reader.ReadToEnd();
var data = JsonConvert.DeserializeObject<Dictionary<string, PropertyDefinition>>(json);
return this.Json(data, JsonRequestBehavior.AllowGet);
}
}
}
public class PropertyDefinition
{
public string datatype;
public bool required;
}
It needs Newtonsoft.JSON nuget package

Angular js and spring mvc

var Buyers = [
{
"first_name" : "Raj",
"last_name" : "Pilla"
},
{
"first_name" : "Ajit",
"last_name" : "Bambaras"
}
];
var Seller = {
"first_name" : "Simon",
"last_name" : "Mathew"
};
How we can post this data to controller using angular js post method also what we need to write in java controller..?
Yes, if you are trying to post multiple objects of the same type. You just need to use a list.
For e.g., in your case it will be :
public #ResponseBody String PostService(#RequestBody List<Seller> seller) {
}
However, if you're trying to send multiple objects of different types, you should instead use List to capture all the objects and then cast them as required.
For e.g.
public #ResponseBody String PostService(#RequestBody List<Object> requestObjects) {
Seller seller = (Seller) requestObjects.get(0);
Buyer buyer = (Buyer) requestObjects.get(1);
}

UpdateOperations embedded array

I have an structure like this:
{
_id: 123,
bs: [
{
_id: 234,
cs: [
{
_id: 456,
ds : [
{
_id: 678,
emails[
"email#gmail.com"
]
}
]
}
]
}
]
}
My classes in Morphia seems like this
#Entity
public class A {
#Id
private ObjectId id;
#Embedded
private List<B> bs;
}
public class B {
private ObjectId id;
#Embedded
private List<C> cs;
}
public class C {
private ObjectId id;
#Embedded
private List<D> ds;
}
public class D {
private ObjectId id;
#Embedded
private List<String> emails;
}
What I am trying to do is insert an email inside embedded array with Morphia without retrieve all element A and use updateFirst.
This is the query I am trying execute
Query<Event> query = this.basicDAO.createQuery();
query.criteria(Mapper.ID_KEY).equal(new ObjectId(aID));
query.criteria("bs.cs.id").equal(new ObjectId(cID));
query.criteria("bs.cs.ds.id").equal(dID);
UpdateOperations<Event> updateOps = this.basicDAO.createUpdateOperations().set("bs.cs.ds.$.emails", email);
this.basicDAO.update(query, updateOps);
I also read about this post Update an item in an array that is in an array with said that
$ operator does not work "with queries that traverse nested arrays".
So I tried something like:
D d = new D(dID);
C c = new C(new ObjectId(cID));
Query<Event> query = this.basicDAO.createQuery();
query.criteria(Mapper.ID_KEY).equal(new ObjectId(aID));
query.field("bs.cs").hasThisElement(c);
query.field("bs.cs.ds").hasThisElement(d);
UpdateOperations<Event> updateOps = this.basicDAO.createUpdateOperations().set("bs.cs.ds.emails", email);
this.basicDAO.update(query, updateOps);
However it still doesn't work. Any idea how solve this? The error message that I receive is cannot use the part ... to transverse the element
Based on your stand-in use case, I think you should "invert" your schema. Each document will represent a lecture and will be tagged with its theme, edition, and event:
{
"_id" : ObjectId("54da1ff0a9ce603a239c3075"),
"event" : "X0004",
"edition" : "A0002,
"theme" : "RT0005",
"votes" : 22
}
event, edition, and theme can be some kind of identifiers, and might be references to event, edition, and theme documents in other collections. To cast a vote for a particular lecture, just update it by _id:
db.test.update({ "_id" : ObjectId("54da1ff0a9ce603a239c3075") }, { "$inc" : { "votes" : 1 } })
While I don't know your full requirements, I think this is a better basic design given your example use case.

How to save an array to a Realm Object

I am new to using Realm. Is there an easy way to save an array to a realm object? I am receiving my data from a JSON REST call:
class SomeClass: RLMObject {
dynamic var id = 0
dynamic var name = ""
dynamic var array: NSArray
func checkForUpdates() {
// Download JSON data here... The results have an array inside of them.
SomeClass.createOrUpdateInDefaultRealmWithObject(SomeNSDictionary)
}
override class func primaryKey() -> String! {
return "id"
}
}
Is it possible to save the array in the JSON results in Realm?
Thanks.
Realm has a special RLMArray type, which allows storing a collection of RLMObject's tied to a parent RLMObject. For example, say you had the following JSON:
{
"name": "John Doe",
"aliases": [
{"alias": "John"},
{"alias": "JD"}
]
}
You could model this with the following classes:
class Alias: RLMObject {
dynamic var alias = ""
}
class Person: RLMObject {
dynamic var name = ""
dynamic var aliases = RLMArray(objectClassName: "Alias")
}
So you could simply create a Person object with the following API call:
Person.createInRealm(realm, withObject: jsonObject)
You can learn more about how RLMArrays work from Realm's reference documentation: http://realm.io/docs/cocoa/0.80.0/api/Classes/RLMArray.html

Resources