NewtonSoft JSON within strings serialization - c#

Given a list of JSON strings is it possible to convert the List to JSON without the serializer thinking that the JSON strings are plain old strings. Using NewtonSoft .NET
Using:
List<string> list = { "{"foo": "bar"}", "[ 1, 2, 3]", "{"biz": "baz", "fiz": ["a", "b", "c"]}";
String json = JsonConvert.SerializeObject(list, Formatting.Indented);
at the current moment I get something like this from json:
"[ \n\r "{"foo": "bar"}", \n\r "[ 1, 2, 3]", ...]"
The serializer treats the json strings like any other strings that have special formatting.
I would like something more like this:
"[
{
"foo": "bar"
},
[
1,
2,
3
],
{
"biz": "baz",
"fiz": [
"a",
"b",
"c"
]
}
]"
something like that with proper indentation.

The idea here is to build the JSON yourself using the Json.NET API instead of writing it by hand. For this, you could use JToken to store your original json strings and then wrap the result inside a JArray. You can then use the ToString method to serialize everything back to JSON when you are done.
var finalString = new JArray(list.Select(JToken.Parse).ToArray()).ToString();

Use this:
JsonSerializer serializer = new JsonSerializer();
serializer.Formatting = Formatting.Indented;

Related

Why JArray.Parse(json_array) gives me "{" in front of the result?

Why JArray.Parse(json_array) gives me "{" in front of the result? (it's like an object)
What I missed?
string _s = "[{\"person\": { \"b2b_pid\": \"157\"} }]";
JArray _j = JArray.Parse(_s);
_j returns:
{[
{
"person": {
"b2b_pid": "157"
}
}
]
}
string _s = "[{\"person\": { \"b2b_pid\": \"157\"} }]";
Simply because you are not passing grammatically correct json object.
in some cases,array cannot be the root of a json object,you have to use dictionary to wrap the array even when you only have one array in your json object.
PS: I notice there is new standard that array top lier is supported.However,be careful of code compatibility.
C# statement JArray.Parse(_s); is adequate intelligent to try to fix your json issue While Key missing.

How to convert List of string(which are already in individual json data) into a single array of json result in c#?

So i have a List of string which holds Indivdual json data, because it is in c# .netCore it already holds escape character('\') for double quotes, but in real it displays correct value that i know, but next i want an array of all these individual json result as a whole json result. what i am doing is directly Serializing this list of string as shown in below code, but it is adding extra escape charaters. is there any other better way of doing this using JsonResult or something?
string json = JsonConvert.SerializeObject(ListOfIndiviualJson);
If I understood correctly, ListOfIndiviualJson is a List<string> that contains strings like
{
"key1": "value",
...
}
And you want to serialise it into something like:
[
{
"key1": "value",
...
},
...
]
You can Parse each of the JSON strings into JObject, then serialise the List<JObject>:
JsonConvert.SerializeObject(ListOfIndiviualJson.Select(JObject.Parse).ToList());
Obviously, if ListOfIndiviualJson actually contains JSON arrays instead of JSON objects, use JArray.Parse.
If I understood you correctly you have a list of json object stored as I string, but now you want it as an array of strings.
string json = #"
[
{ ""test1"" : ""desc1"" },
{ ""test2"" : ""desc2"" },
{ ""test3"" : ""desc3"" }
]";
JArray a = JArray.Parse(json);
var _len = a.Count; // will be 3
Then you can convert it to a string and in json view you will see normal output.

Json.NET deserializing contents of a JObject?

If I have a JObject, which contains the property "Fields".
How do I pull out the contents of this property to an object[] with deserialized elements?
It seems like no matter what I do, I only get arrays of other JObjects.
myJObject["Fields"] {
"$type": "System.Object[], mscorlib",
"$values": [
123,
"hello"
]
}
In this case, I want to get an object array containing a long 123 and the string "hello".
Use ToObject():
var array = myJObject["Fields"].ToObject<object[]>();
Debug.Assert(array[0].Equals(123L)); // No assert
Debug.Assert(array[1].Equals("hello")); // No assert

Unable to Parse this Json string in c#

I tried using Newtonsoft.Json to deserialize this json string, but I'm not getting the desired output.
my json string is
[
{
"id": 1,
"key": "Residential Homeowner",
"i18nText": "unknown message code DB_ENUM_UserType_residentialhomeowner",
"i18nKey": "DB_ENUM_UserType_residentialhomeowner"
},
{
"id": 8,
"key": "VAR Dealer \/ Builder",
"i18nText": "unknown message code DB_ENUM_UserType_vardealer\/builder",
"i18nKey": "DB_ENUM_UserType_vardealer\/builder"
},
{
"id": 2,
"key": "Administrator",
"i18nText": "unknown message code DB_ENUM_UserType_administrator",
"i18nKey": "DB_ENUM_UserType_administrator"
},
{
"id": 9998,
"key": "TempGuidUser",
"i18nText": "unknown message code DB_ENUM_UserType_tempguiduser",
"i18nKey": "DB_ENUM_UserType_tempguiduser"
},
{
"id": 9999,
"key": "GuidUser",
"i18nText": "unknown message code DB_ENUM_UserType_guiduser",
"i18nKey": "DB_ENUM_UserType_guiduser"
}
]
I just want the value of key when value of id=1. Generally json starts with {}(curly bracket) but here it is like [](square bracket). I've seen many examples but none worked for me.
Generally json starts with {} (curly bracket), but here it is like [] (square bracket).
This is because you got an array of objects, not a single object. Arrays are serialized with square brackets around them. You should deserialize it into an array, and then grab the object at the index of interest.
This is a related post that addresses JSON parsing in C#: C# JSON Parsing.
If the brackets are a problem, simply use:
string json = inputJson.Trim().Trim('[',']');
If the id can have a minimum value of 1, then this should work:
string GetKey(string inputJson)
{
string key = inputJson.Substring(inputJson.IndexOf("key")+5);
key = key.Substring(key.IndexOf("\""), key.IndexOf(",")-key.IndexOf("\""));
key = key.Trim('\"');
return key;
}
If you are only interested in a single value from that larger JSON value, you may want to try Linq to JSON which would allow you to query over the JSON without deserializing everything.
Example:
JArray values = JArray.Parse(json);
string key;
var keyObject = values.FirstOrDefault(p => (int)p["id"] == 1);
if (keyObject != null)
{
key = (string)keyObject["key"];
}
[] is to define a json object array. Your output should be an array. Traverse through the array like:
for(var i=0; i<output.Length; i++)
{
if(output[i].id == "1") // desired id
{
Console.WriteLine(output[i].key);// use it as you wish
}
}
and use the found objects key.

JSON parse exception using System.Json

I get an error while parsing a json string into an object. I am using system.json to parse the json string.
The JSON file: (NOTE: I cannot change the structure of this json file because it is generated)
{
title: "My Title",
log: "",
nid: "1234",
type: "software",
language: "EN",
created: "1364480345",
revision_timestamp: "1366803957",
body: {
und: [
{
value: "abc",
summary: "def"
}
]
}
}
The C# code:
string jsonString = new WebClient().DownloadString(".......MyJson.json"); //For test purpose
var obj = JsonObject.Parse (jsonString); ///<--- At this line the exception is thrown
The Exception:
System.ArgumentException has been thrown.
Invalid JSON string literal format. At line 1, column 2
How to solve this?
Thanks in advance!
You can't. That isn't valid json. Field names must be enclosed in quotes. All json parsing tools will throw when trying to parse that.
You could process it and turn it to valid json before deserializing, but really, you need to correct it API side. No clients will work with that.
How to solve this?
(NOTE: I cannot change the structure of this json file because it is generated)
Easy, use json.Net. it works without any problem with your json
var j = JObject.Parse(jsonString);
You can even use dynamic keyword
dynamic j = JObject.Parse(jsonString);
Console.WriteLine("{0},{1}", j.title, j.body.und[0].value);

Categories