Concatenate JsonRepresentation - json

How can I concatenate multiple JsonRepresentation Object into one, without building my own string parser?
Say I have two JsonRepresentation objects
obj1 = {"name":"obj1"};
obj2 = {"name":"obj2"};
I would like to get the result concatenation as:
{
{"name":"obj1"},
{"name":"obj2"}
}
Reading the JsonRepresentation, there is no easy way to do this except by doing some string manipulation. Am I right?
Thanks

If you're referring to this JsonRepresentation class, and you want to merge the 2 objects into an array, then you should be able to do it as follows:
JSONObject jsonObj1 = obj1.toJsonObject();
JSONObject jsonObj2 = obj2.toJsonObject();
JSONArray jsonArray = new JSONArray().append(jsonObj1).append(jsonObj2);
JsonRepresentation jsonConcat = new JsonRepresentation(jsonArray);
Note: I haven't actually used the library, but if it behaves per the API, this should be pretty straightforward.

Related

LINQ on JArray always returning null

I'm trying to parse some Json in Xamarin.Forms
I'm pretty new to Xamarin, though not to .net
Here's my simple dimple code
var htc = new HttpClient();
var rsp = await htc.GetStringAsync("myurl.com");
JArray lists = JArray.Parse(rsp);
var c = lists.Count();
var l = lists.ToList();
var w=lists.Where(x => true);
Even though c returns the correct count of items in the list, l & w are both null
How come? and how do I fix it?
Thanks!
PS. What I'm really trying to do is bind a ListView to a JArray, but it seems impossible directly,(Text={Binding MyPropertyName} crashes the app). so I'm trying to run a Select on the JArray to convert to a KeyValuePair. If you have any ideas to bind directly, that would be best!
UPDATE
The issue seems even odder
I tried this
var kvlist = new List<KeyValuePair<string, string>>();
foreach (JObject ll in lists)
{
kvlist.Add(new KeyValuePair<string, string>(ll["Name"].ToString(), ll["Name"].ToString()));
}
Here at least the iteration works nicely, but the kvlist is null the entire time. Trying to evaluate the kvlist variable, I get:
Unable to cast object of type 'System.RuntimeType' to type
'Mono.Debugger.Soft.TypeMirror'.
What can the matter be?
Thanks again!
You should not directly call .ToList on object type of JArray rather you should Select List of type you need. For ex.
var l = lists.Select(c => new MyList
{
Item1 = c.Value<int>("ItemName1"),
Item2 = c.Value<string>("ItemName2")
}).ToList(); //Replce MyList with your class name
On the second case where w is null, after getting list l you need to specify attribute, based of what you are using where clause. For ex.
var w=l.Where(x =>x.isAdmin==true); //l is list you selected above
Hope it help you.
Solution:
You can use code below to convert a JArray to a list<T>:
List<T> t =lists.ToObject<List<T>>();
Refer: https://www.newtonsoft.com/json/help/html/ToObjectType.htm
You could also use JsonConvert.DeserializeObject to convert it directly into the desired type. You have to define a jsonModel class with the same structure of your json fisrtly.
List<jsonModel> modelList = JsonConvert.DeserializeObject<List<jsonModel>>(jsonStr);
Refer :https://www.newtonsoft.com/json/help/html/SerializingCollections.htm
The documentation seems to indicate that JArray has properties for .Count, but no overload method because it does not implement IEnumerable, however as alluded to in the comments, it does implement the JToken type (which JArray is a collection of) and implements IEnumerable.
See the following documentation for JToken: https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Linq_JToken.htm
and JArray respectively:
https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Linq_JArray.htm
The preferred mechanism is to create a strong type and then run .ToObject();
You can access JArray.ChildrenTokens which may help

How to remove escaping slashes from a json inside another json?

I have the following json, that is being populated by:
new Gson().toJson(batch.getProducts());
But when im adding it to my main JSONObject, the fact that it's a value of a json is doing all the json (even the keys) be escaped.
{"name":"Ufud","store":2,"products":"[{\"name\":\"Test2\",\"stock\":2,\"value\":19.9},{\"name\":\"Test2\",\"stock\":2,\"value\":19.9},{\"name\":\"Teste2\",\"stock\":2,\"value\":19.9}]"}
Is there any method to prevent this?
If you're going to manipulate your json in future you may consider converting it not into a string, but into a JsonElement which can be quite easily added to already existing JsonObject
JsonObject mainObject = getMainObject(); //method which creates your main object. You can change it to variable reference
JsonElement productsElement = new Gson().toJsonTree(batch.getProducts()); //converting your object into JsonElement
mainObject.add("products", productsElement); //insering products element into object.
String json = new Gson().toJson(mainObject); //converting object with products element into a json string

POCO::PostgreSQL retrieve JSON datatype

What is the best way to retrieve data from JSON field in PostgreSQL using POCO framework?
The only way I see is:
Poco::Data::RecordSet rs(session, sql);
rs.moveFirst();
string value = rs[0].convert<std::string>(); // get JSON as string
Poco::JSON::Parser parser;
parser.parse(value);
Poco::Dynamic::Var result = parser.result();
// now we can extract Object, Array and so on
Direct extract
Poco::JSON::Object object = os[0].extract<Poco::JSON::Object>()
throws Can not convert [ERRFMT] to [ERRFMT] exception.
Any better solution?
Var result = parser.parse(value);
Object::Ptr object = result.extract<Object::Ptr>();

want to bind string using comma separated using for loop

string json="[{\"ParentId\":\"a9764da3147845c184bd272cef6a5937\",\"Path\":\"/LMS/Cabinet/bdc2cd8e1da3451c84e332d1aa74f605\",\"CreatedBY\":\"admin\",\"IsActive\":\"Y\",\"CabinetName\":\"LMS\",\"FolderTag\":\"IT mobile computing,Comm Skills\",\"Name\":\"JAVA\",\"UpdatedBY\":\"\",\"Type\":\"Folder\",\"IsDelete\":\"N\",\"UpdatedON\":\"\",\"Id\":\"bdc2cd8e1da3451c84e332d1aa74f605\",\"CreatedON\":\"2015_09_08-11:19:50\",\"TemplateId\":\"dd42c8a71a954c1d948ef35492ee1242\" },{\"ParentId\":\"a9764da3147845c184bd272cef6a5937\",\"Path\":\"/LMS/Cabinet/3aae020c256f4dc1ab705af67bede2c7\",\"CreatedBY\":\"admin\",\"IsActive\":\"Y\",\"CabinetName\":\"LMS\",\"FolderTag\":\"IT mobile computing,Comm Skills\",\"Name\":\"Spring\",\"UpdatedBY\":\"\",\"Type\":\"Folder\",\"IsDelete\":\"N\",\"UpdatedON\":\"\",\"Id\":\"3aae020c256f4dc1ab705af67bede2c7\",\"CreatedON\":\"2015_09_04-16:58:05\",\"TemplateId\":\"dd42c8a71a954c1d948ef35492ee1242\"},{\"ParentId\":\"a9764da3147845c184bd272cef6a5937\",\"Path\":\"/LMS/Cabinet/c139b33a22a94a25bf624b94450aee3e\",\"CreatedBY\":\"admin\",\"IsActive\":\"Y\",\"CabinetName\":\"LMS\",\"FolderTag\":\"Social Skills\",\"Name\":\"SQL\",\"UpdatedBY\":\"\",\"Type\":\"Folder\",\"IsDelete\":\"N\",\"UpdatedON\":\"\",\"Id\":\"c139b33a22a94a25bf624b94450aee3e\",\"CreatedON\":\"2015_09_04-16:54:44\",\"TemplateId\":\"dd42c8a71a954c1d948ef35492ee1242\"}]";
This is my JSON string and I want to only "Name" field with comma separated into another variable.
For example, example:
string res={"JAVA","SPRING","SQL"}
What language are you trying to do this in? My first guess is javascript but i wasnt sure.
If its JavaScript, then you can get starten by turning the json string into a JavaScript object like this:
var jsonElements = JSON.parse (json);
From there its just looping and collecting the name property from each object.
Now we'll do this from C# instead
Ok, since you are doing the parsing from C# you would want this code instead:
string json = "[{\"ParentId\":\"a9764da3147845c184bd272cef6a5937\",\"Path\":\"/LMS/Cabinet/bdc2cd8e1da3451c84e332d1aa74f605\",\"CreatedBY\":\"admin\",\"IsActive\":\"Y\",\"CabinetName\":\"LMS\",\"FolderTag\":\"IT mobile computing,Comm Skills\",\"Name\":\"JAVA\",\"UpdatedBY\":\"\",\"Type\":\"Folder\",\"IsDelete\":\"N\",\"UpdatedON\":\"\",\"Id\":\"bdc2cd8e1da3451c84e332d1aa74f605\",\"CreatedON\":\"2015_09_08-11:19:50\",\"TemplateId\":\"dd42c8a71a954c1d948ef35492ee1242\" },{\"ParentId\":\"a9764da3147845c184bd272cef6a5937\",\"Path\":\"/LMS/Cabinet/3aae020c256f4dc1ab705af67bede2c7\",\"CreatedBY\":\"admin\",\"IsActive\":\"Y\",\"CabinetName\":\"LMS\",\"FolderTag\":\"IT mobile computing,Comm Skills\",\"Name\":\"Spring\",\"UpdatedBY\":\"\",\"Type\":\"Folder\",\"IsDelete\":\"N\",\"UpdatedON\":\"\",\"Id\":\"3aae020c256f4dc1ab705af67bede2c7\",\"CreatedON\":\"2015_09_04-16:58:05\",\"TemplateId\":\"dd42c8a71a954c1d948ef35492ee1242\"},{\"ParentId\":\"a9764da3147845c184bd272cef6a5937\",\"Path\":\"/LMS/Cabinet/c139b33a22a94a25bf624b94450aee3e\",\"CreatedBY\":\"admin\",\"IsActive\":\"Y\",\"CabinetName\":\"LMS\",\"FolderTag\":\"Social Skills\",\"Name\":\"SQL\",\"UpdatedBY\":\"\",\"Type\":\"Folder\",\"IsDelete\":\"N\",\"UpdatedON\":\"\",\"Id\":\"c139b33a22a94a25bf624b94450aee3e\",\"CreatedON\":\"2015_09_04-16:54:44\",\"TemplateId\":\"dd42c8a71a954c1d948ef35492ee1242\"}]";
dynamic jsonObj = (JArray)JsonConvert.DeserializeObject(json);
List<string> names = new List<string>();
foreach (JObject item in jsonObj)
{
names.Add(item["Name"].ToString());
}
Deserialize the string and cast it to a JArray. Then foreach element in the array, we look at the Name property of the element. I tested this code in visual studio and it appears to work.

difference between json string and parsed json string

what is the difference between json string and parsed json string?
for eg in javascript suppose i have a string in the json format say [{},{}]
parsing this string will also produce the same thing.
So why do we need to parse?
It's just serialization/deserialization.
In Javscript code you normally work with the object, as that lets you easily get its properties, etc, while a JSON string doesn't do you much good.
var jsonobj = { "arr": [ 5, 2 ], "str": "foo" };
console.log(jsonobj.arr[1] + jsonobj.str);
// 2foo
var jsonstr = JSON.stringify(jsonobj);
// cannot do much with this
To send it to the server via an Ajax call, though, you need to serialize (stringify) it first. Likewise, you need to deserialize (parse) from a string into an object when receiving JSON back from the server.
Great question. The difference is transfer format.
JSON is only the 'Notation' of a JavaScript Object, it is not actually the JavaScript 'object-literal' itself. So as the data is received in JSON, it is just a string to be interpreted, evaluated, parsed, in order to become an actual JavaScript 'Object-Literal.
There is one physical difference between the two, and that is quotation marks. It makes sense, that JSON needs to be a string to be transferred. Here is how:
//A JavaScript Object-Literal
var anObj = { member: 'value'}
//A JSON representation of that object
var aJSON = { "member":"value" }
Hope that helps. All the best! Nash
I think a parsed json string should be the string data into the actual javascript objects and data arrays (or whichever language the json string contains)
The JSON object contains methods for parsing JSON and converting values to JSON.
It can't be called or constructed, and aside from its two method properties it has no interesting functionality of its own.
JSONParser parser = new JSONParser();
Object object = parser.parse(Message.toString());
JSONObject arObj = (JSONObject) object;