I'm doing my first steps with Newtonsoft Json parser, but there are very fex examples on VB.net apperently. I just want to parse a string, and then I want to be able to loop throught the different list
This is my code :
Dim JSON As String
Dim values As Newtonsoft.Json.Linq.JObject
JSON = "{'mailadresses': { 'List1':{'Stefaan Somers': 'JoskeVermeulen#gmail.com', 'Markske': 'mdtre#gmail.com' }, 'List2':{'Stefaan XSomers': 'Test#gmail.com', 'xMarkske': 'mdrmdtre#gmail.com' }}"
values = JObject.Parse(JSON)
It directly gives me the error when running :
Unexpected end of content while loading JObject. Path 'mailadresses', line 1, position 221.
Any idea also on how to loop through the different elements. I don't want to cast to a custom class, as described in many samples
Your json isnt valid according to jsonlint.
try this instead:
{
"mailadresses": {
"List1": {
"StefaanSomers": "JoskeVermeulen#gmail.com",
"Markske": "mdtre#gmail.com"
},
"List2": {
"StefaanXSomers": "Test#gmail.com",
"xMarkske": "mdrmdtre#gmail.com"
}
}
}
Related
My datasource creates the JSON representing an array of integers as "1,2,3,4,5". I can't do anything about this (Like changing it to [1,2,3,4,5]), it is an enterprise CMS that we have to just deal with.
I'm trying to read up on how the newtonsoft ToObject method handles the following code:
JValue theValue = new JValue("1,2,3")
List<int> x = theValue.ToObject<List<int>>();
I get a Newtonsoft.Json.JsonSerializationException. Could not cast or convert from System.String to System.Collections.Generic.List`1[System.String]. I understand this fully, but I'd like to know if the Newtonsoft JSON libraries have a built in way to convert from a comma delimited string to a List.
I'd like to think there's a better way than trying to check if the variable is a comma delimited list or not and then converting it to a List<> manually, or maybe a JArray, but I've been wrong before !
EDIT
I wanted to share my solution:
dynamic theValue = new JValue("1,2,3,4"); /// This is just passed in, i'm not doing this on purpose. Its to demo.
if (info.PropertyType == typeof (List<int>))
{
if (info.CanWrite)
{
if (theValue.GetType() == typeof (JValue) && theValue.Value is string)
{
theValue = JArray.Parse("[" + theValue.Value + "]");
}
info.SetValue(this, theValue.ToObject<List<int>>());
}
} else {
// do other things
You have three problems from what I can see:
You should be using JArray not JValue. You are intending this to be an array of things, so you need to use the equivalent class in Newtonsoft to represent an array. (A JValue, as best I can tell, represents a simple type--e.g. string, number, Date, etc.)
You should use the Parse method versus using the constructor. Parse will read the content of the string as an array, however...
...in order for it to do that, you will need to surround the data that you get with the square brackets or JArray can't correctly the parse the data. There is no need to fiddle with the CMS; just do a string concat before you parse.
e.g.
JArray theValue = JArray.Parse("[" + "1,2,3" + "]");
I have been trying to find the question to my answer but I'm unable to and finally I'm here. What I want to do is access the value passed to a webpage (GET, POST request) using asp.net. To be more clear, for example:
URL: http://www.foobar.com/SaleVoucher.aspx?sr=34
Using asp.net I want to get the sr value i.e 34.
I'm from the background of C# and new to ASP.NET and don't know much about ASP.NET.
Thanx.
Can you refer to this QueryString
Here he says how to access the query string using:
Request.Url.Query
That is not called a Header, but the Query String.
the object document.location.search will contain that and the javascript to get any query string value based on the key would be something like:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
code from other question: https://stackoverflow.com/a/901144/28004
I Have an asp.net mvc api controller method that has a List as its return method. When called it returns this json data:
[
{
"AreaName": null,
"AreaId": 0,
"DestinationName": "Alanya",
"DestinationId": 14,
"CountryName": "Tyrkiet",
"CountryId": 15
},
{
"AreaName": null,
"AreaId": 0,
"DestinationName": "Antalya",
"DestinationId": 113,
"CountryName": "Tyrkiet",
"CountryId": 15
}
]
Earlier when I had this method in an asp.net mvc it would look similar to this:
earlier json data:
{
"ContentEncoding":{
"IsSingleByte":true,
"BodyName":"iso-8859-1",
"EncodingName":"Western European (Windows)",
"HeaderName":"Windows-1252",
"WebName":"Windows- 1252",
"WindowsCodePage":1252,
"IsBrowserDisplay":true,
"IsBrowserSave":true,
"IsMailNewsDisplay":true,
"IsMailNewsSave":true,
"EncoderFallback":{
"MaxCharCount":1
},
"DecoderFallback":{
"MaxCharCount":1
},
"IsReadOnly":true,
"CodePage":1252
},
"ContentType":"application/json;",
"Data":
and then the above list would be added inside of the Data wrapper
My question is - how do I get this "wrapper" format back when using the asp.net mvc web api ?
Your JSON is a normal format for list of objects and the second one, older represents an object. So when you need it - just return object.
Probably, in the older version (normal mvc) you did return something like this:
return JsonResult(new { Data = myList });
now, in WebApi, you do this:
return myList;
That explains why the old result has all that formatting around. To get back the old wrapper in your WebApi, I guess you would simply do something like this:
return new { Data = myList };
If the above does not work, try the following:
Change the return type of your method to HttpResponseMessage
use this:
return Request.CreateResponse(HttpStatusCode.OK, new { Data = myList });
I don't have anything to debug at the moment but both of the above should work. If they don't, it is probably because the serialization-deserialization does not like anonymous objects (this may give you more problems with XML than JSON actually).
Anyway, in my opinion it is a lot easier to live with the new version of your object, mainly because it does NOT have a (noisy) wrapper around :)
You can create your own returning type, something like this:
public class InvoiceResult
{
public int numberResultTotal;
public int numberResultPaged;
public List<InvoiceDTO> results;
}
ASP.NET Web API will convert it to JSON, XML or any other format and your client will get something like this:
<InvoiceResult>
<numberResultPaged>20</numberResultPaged>
<numberResultTotal>999999</numberResultTotal>
<results>
<InvoiceDTO>
<ID>110</ID>
<Active>2</Active>
<Date>01/01/2010</Date>
</InvoiceDTO>
<InvoiceDTO>...</InvoiceDTO>
<InvoiceDTO>...</InvoiceDTO>
<InvoiceDTO>...</InvoiceDTO>
</results>
</InvoiceResult>
There is an example that I have seen in a number of places for encoding a Map as follows:
#import('dart:uri');
String encodeMap(Map data) {
return Strings.join(data.getKeys().map((k) {
return "${encodeUriComponent(k)}=${encodeUriComponent(data[k])}";
}), "&");
}
I'm running what appears to be the latest Dart editor (version 0.2.9_r 16323)
in the above example, for Dart M2, I believe that data.getKeys() has been changed to data.keys() which I have altered.
However, I get an error when running it in the Editor:
Exception: NoSuchMethodError : method not found: 'call'"
I have 2 questions:
I'm wondering if this above code should still work in M2 with the change indicated (Map.keys())?
I'm wondering if this above code does something different to: JSON.stringify(data);
Any other pointers are welcome.
TIA.
Two changes to do :
import syntax has changed.
getKeys() method became a getter called keys.
A working version :
import 'dart:uri';
String encodeMap(Map data) {
return Strings.join(data.keys.map((k) {
return "${encodeUriComponent(k)}=${encodeUriComponent(data[k])}";
}), "&");
}
The String generated by this encodeMap is quite different from the one generated by JSON.stringify as you can see in the bellow snippet :
main() {
final map = {"a":"b", "c":"d"};
assert(encodeMap(map) == "a=b&c=d");
assert(JSON.stringify(map) == '{"a":"b","c":"d"}');
}
I am using the JSON2 script in an asp page to parse JSON post data.
After parsing the data, I have an object in VBScript that allows for notations such as:
jsonData.key
I wish to parse through all the keys, however, I have no knowledge of the key names.
How would I go about doing this?
Example JSON:
{ "dbtable":"TABLE1", "dbcommand": "INSERT", "dbfilter": "ID" }
Thanks
You need to enumerate the property names of the object however this is a very alien thing to do in VBScript. You will need to build some other Jscript functions to assist converting the object into something more easily consumed in VBScript.
If the data is really as simplistic as the example in the question then you could use this function:-
function toDictionary(o)
{
var result = Server.CreateObject("Scripting.Dictionary");
for (var key in o)
result.Add(key, o[key]);
return result;
}
Now in VBScript:-
Dim myData: Set myData = toDictionary(jsonData);
For Each Key In myData
'' // Each Key is a property for jsonData
Next