deserialize json to general object (without predefined schema) - json

I'm trying to use json.net.
I'd like to get a string (in json format) and convert it to general json object, without predefined schema.
somelting like
var jsonString = #"{\""id\"": 1,\""name\"": \""A green door\""}";
var jsonMessage = JsonConvert.DeserializeObject<JObject>(jsonString);
var myValue = jsonMessage["name"]
Is that something doable? didn't make it work

Your string is malformed, try this string instead:
var jsonString = "{\"id\": 1,\"name\": \"A green door\"}";
You could also shorten this a little bit:
string name = JObject.Parse(jsonString)["name"].ToObject<string>();

Related

Insert json string to mongoDB

I am new to Scala and MongoDB. I am writing a Scala program to read JSON string (it can be nested json string also) and insert the same to Mongo DB.
I tried below few things but its not working.
1) Tried to create an Document for the JSON string as below:
var document = (DBObject) JSON.parse(jsonString)
but getting the error
"value JSON is not member of object com.mongodb.DBObject".
2) Also tried with bson.Document as below but still can get it working
var myDoc = (Document.parse(schemajson))
Can anyone help me out on this? Please let me know if my approach is correct. If not the please do let me know what all things I need to do.
adding code:
val hadoopRDD = sc.textFile(data_file).foreach(line =>
{
data_array.clear
line.split("\t").foreach(word => data_array += word)
println(data_array)
var final_json = (schemajson.format(data_array: _*))
var document = (DBObject) JSON.parse(jsonString)
in above code final_json is the string having Json string like {"name": xyz, "age": 22}
I found the answer and below is the solution which worked for me.
I was simply using
var document = (DBObject) JSON.parse(jsonString)
which was causing error.
Instead we need to provide asInstanceOf[DBObject] which worked in my case
val dbObject: DBObject = JSON.parse(final_json_str).asInstanceOf[DBObject]

JSON String parsing each character as an object

I have a JSON file that contains what I believe to be a correct JSON string:
{"title": "exampleTitle", "tipTitle": "exampleTipTitle", "tip": "exampleTip"}
I'm trying to parse said file and take out the 3 values then store them in variables, however currently, it parses each individual character as a separate object, therefore:
JSONobj[1] = "
and so on. Assuming that currentLocation = the directory location of the json file.
Code
var jsonLocation = currentLocation + "json.txt";
var request = new XMLHttpRequest();
request.open("GET", jsonLocation, false);
request.send(null);
var returnValue = request.responseText;
var JSONobj = JSON.parse(JSON.stringify(returnValue));
var headerTitle = JSONobj[0];
A few clarifications, the stringify is in because it was throwing an unexpected token error. I've tried changing the file tile to .json instead but that also makes no difference. "It also gives off a XMLHttpRequest on the main thread is deprecated" but I'm not particularly sure how to solve that issue. Any help would be appreciated.
var returnValue = request.responseText;
Here returnValue is a string of JSON.
"{\"title\": \"exampleTitle\", \"tipTitle\": \"exampleTipTitle\", \"tip\": \"exampleTip\"}
var JSONobj = JSON.parse(JSON.stringify(returnValue));
Here you convert the string of JSON to JSON. So you have a JSON string representing a string, and that string is a representation of a data structure in JSON.
"\"{\\"title\\": \\"exampleTitle\\", \\"tipTitle\\": \\"exampleTipTitle\\", \\"tip\\": \\"exampleTip\\"}"
Then you parse it and convert it back to the original string of JSON.
"{\"title\": \"exampleTitle\", \"tipTitle\": \"exampleTipTitle\", \"tip\": \"exampleTip\"}
So you end up back where you start.
Just don't use JSON.stringify here, and you'll convert your JSON to a JavaScript object:
var javascript_object = JSON.parse(returnValue);
Then you have an object, but it doesn't have a 0 property so it doesn't make sense to access it with javascript_object[0]. The properties have names, such as javascript_object.title.
Your JSON doesn't describe an array, so indexing into it with an index like 0 doesn't make sense. Your JSON describes an object, which will have properties with the names title, tipTitle, and tip.
Additionally, you're overdoing your parsing: You just want to parse, not stringify (which is the opposite of parsing):
var JSONobj = JSON.parse(returnValue);
So:
var JSONobj = JSON.parse(returnValue);
var headerTitle = JSONobj.title;
console.log(headerTitle); // "exampleTitle"
Side note: By the time you've assigned it to the variable you've called JSONobj, it isn't JSON anymore, it's just a normal JavaScript object, so that name is a bit misleading. If you're writing source code, and you're not dealing with a string, you're not dealing with JSON anymore. :-)

Parse an entire JSON array into a table using 1 key

I need some help with parsing JSON in Swift.
[{"Database":"information_schema"}
{"Database":"Tonysnasa"},
{"Database":"camaleonsystems"},
{"Database":"camaleonsystems_back"},
{"Database":"camaleonsystemsfortest"}]
^ - Above is my JSON
v - Below is my Swift code.
let jsonDB: String! = jsonResult[0]["Database"] as NSString
println(jsonDB)
self.DBList.append(jsonDB)
I want to parse all of the "Database:" entries. When I try the method above, I am only able to parse information_schema.
How can I parse all the "Database:"'s into my table?
looks like it is an array of dictionaries,to get them all you should be able to use:
var jsonDB : [Dictionary<String, String>] = jsonResult
for currentDictionary in jsonDB{
var currentEntry = currentDictionary["Database"] as String
println(currentEntry)
self.DBList.append(currentEntry)
}

Receiving JSON in salesforce

I am trying to receive a JSON string in salesforce by converting a blob in the body of an Http request. However, when I convert the blob to a string there are \ characters that get inserted into the request which prevents me from parsing.
I then tried to take the string and remove all \ characters... that didn't work either.
RestRequest req = RestContext.request;
Blob jsonBlob = req.requestBody;
String jsonString = jsonBlob.toString();
return jsonString;
The original string (the one that is received as a blob) looks like this:
{"putTimeCard":{"timecard":{"timeCardID": "","employeeID": ""}}
And after converting to a salesforce string and assigned to the jsonString is altered to:
{\"putTimeCard\":{\"timecard\":{\"timeCardID\": \"\",\"employeeID\": \"\"}}
Has anyone found a solution for this?
Thanks
The JSON Deserializer can parse the string with the escape characters. You can either deserialize into an object like so:
String jsonString = '{\"putTimeCard\":{\"timecard\":{\"timeCardID\": \"\",\"employeeID\": \"\"}}}'
Timecard t = (Timecard) JSON.deserialize(jsonString, Type.forName('Timecard'));
or if you just want a map of objects you can do the following:
String jsonString = '{\"putTimeCard\":{\"timecard\":{\"timeCardID\": \"\",\"employeeID\": \"\"}}}'
Map<String, Object> m = (Map<String, Object>) JSON.deserializeUntyped(jsonString);

Error while using Newtonsoft.Json to parse a Json string

My JSON string looks like this. Please note that it has escape characters.
string json = "\"{\\\"Status\\\":true,\\\"ID\\\":24501}\"";
When I use the Parse method like below I run into an error stated below:
JObject o = JObject.Parse(json);
Error reading JObject from JsonReader. Current JsonReader item is not an object: String
How do I get rid of this error or is there any other method to parse my json string and fetch the values?
Remove first and last quotes:
string json = "{\"Status\":true,\"ID\":24501}";
See the Json format here.
It seems like your object is double encoded. Try:
string json = "{\"Status\":true,\"ID\":24501}";
You need something like this
json = json.Replace(#"\", string.Empty).Trim(new char[]{'\"'})
in here format should be something like this:
string jsonNew = #"{'Status': True,'ID': 24501 }";
As SolarBear says in his comment, the problem is double-escaping.
To get the proper format, like this:
string json = "{\"Status\":true,\"ID\":24501}";
Do something like this:
json = json.Replace("\\\\", "\\");
Had similar issue today. My solution to this is contained in this extension method (using c#):
public static class StringExtensions
{
public static string RemoveDoubleEncoding(this string text)
{
if(string.IsNullOrEmpty(text))
return string.Empty;
var result = text.TrimStart('\"').TrimEnd('\"');
result = result.Replace(#"\", string.Empty);
return result;
}
}