How to serialize a JObject without the formatting? - json

I have a JObject (I'm using Json.Net) that I constructed with LINQ to JSON (also provided by the same library). When I call the ToString() method on the JObject, it outputs the results as formatted JSON.
How do I set the formatting to "none" for this?

Call JObject's ToString(Formatting.None) method.
Alternatively if you pass the object to the JsonConvert.SerializeObject method it will return the JSON without formatting.
Documentation: Write JSON text with JToken.ToString

You can also do the following;
string json = myJObject.ToString(Newtonsoft.Json.Formatting.None);

you can use JsonConvert.SerializeObject()
JsonConvert.SerializeObject(myObject) // myObject is returned by JObject.Parse() method
JsonConvert.SerializeObject()
JObject.Parse()

Related

JSON is printed with backslashes

{"externalQueryDate":"4018-11-23"}
this is my json string, which is in a column of mysql.
I get it with creditRisk.getCreditRiskDataCodeBased()
and in javascript or in swagger, i see with backslashes:
"{\"externalQueryDate\":\"4018-11-23\"}"
I can use JSON.parse in frontend but , i want to solve this is backend.
even
for
StringWriter sw = new StringWriter();
objectMapper.writer().writeValue(sw, creditRisk.getCreditRiskDataTermBased());
it writes this:
"responseCode": "\"{\\\"externalQueryDate\\\":\\\"4018-11-23\\\"}\""
I tried those
objectMapper.readTree(creditRisk.getCreditRiskDataCodeBased()).toString()
and
objectMapper.writer().writeValue(sw, creditRisk.getCreditRiskDataTermBased());
and
#JsonRawValue
#JsonValue
How can i solve this?
In mysql, it is also without slashes
If you want to parse the json string with jackson objectMapper you need to use 'read' and tell it what class to use to create the parsed object from.
So in your case you could do something like
ObjectMapper objectMapper = new ObjectMapper();
String json = "{\"externalQueryDate\":\"4018-11-23\"}";
Map map = objectMapper.readValue(json, Map.class);
System.out.print(map.get("externalQueryDate"));
I've just used a Map here as I don't know what class you're wanting to parse the json into. If you have a class with an externalQueryDate field you can read into that. You could also use #JsonFormat on the field to tell it what the date format is if you want to parse the value straight into a LocalDate field.
I suggest you write a few simple unit tests to get the hang of escaped quotes in strings. It looks like they're causing you some confusion.

Is there a way to define a to_json handler in GDScript?

I'm new to GDScript and am looking at how best to save data to a text file. to_json works well for basic types but I just get a reference id for any custom classes. I'd ideally like to pass a dictionary of data including some custom class elements to to_json and let it convert it all at once.
Like other languages provide a toString method for printing an object, is there anything that would let me specify how a class instance should be converted to JSON?
Yeah, you would just add something like the following to your class:
func to_json():
var data = {} #must create it as a dictionary or array
data["health"] = 5
#code to create json
var json
json = data.to_json() #dictionaries automatically have this function
return json
I think it really is that simple :)
Please note: I have not tested this code.

JSON Parse using C#

Anybody has any idea how to parse below type of JSON object where same object named objects are present in master object. Below is an example
abc{
"abc":"123"
}
How to parse the child abc value?
You can use Json.NET it is vary easy to use. Json.NET handles JSON arrays natively, and will parse them into any type, string,int etc.
Are you currently using a JSON framework? Maybe check out Json.NET: http://www.newtonsoft.com/json.
Then you could do something like:
int onetwothree = jObject.SelectToken("abc.abc");
You can use http://www.newtonsoft.com/json to parse any json string on c#:
Your example :
var jsonString= "{\"abc\":{ \"abc\":\"123\" }}";
var jObj = JObject.Parse(jsonString);
var abcValue = jObj.SelectToken("abc.abc").Value<string>();

How can I define a ReST endpoint that allows json input and maps it to a JsonSlurper

I want to write an API ReST endpoint, using Spring 4.0 and Groovy, such that the #RequestBody parameter can be any generic JSON input, and it will be mapped to a Groovy JsonSlurper so that I can simply access the data via the slurper.
The benefit here being that I can send various JSON documents to my endpoint without having to define a DTO object for every format that I might send.
Currently my method looks like this (and works):
#RequestMapping(value = "/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
ResponseEntity<String> putTest(#RequestBody ExampleDTO dto) {
def json = new groovy.json.JsonBuilder()
json(
id: dto.id,
name: dto.name
);
return new ResponseEntity(json.content, HttpStatus.OK);
}
But what I want, is to get rid of the "ExampleDTO" object, and just have any JSON that is passed in get mapped straight into a JsonSlurper, or something that I can input into a JsonSlurper, so that I can access the fields of the input object like so:
def json = new JsonSlurper().parseText(input);
String exampleName = json.name;
I initially thought I could just accept a String instead of ExampleDTO, and then slurp the String, but then I have been running into a plethora of issues in my AngularJS client, trying to send my JSON objects as strings to the API endpoint. I'm met with an annoying need to escape all of the double quotes and surround the entire JSON string with double quotes. Then I run into issues if any of my data has quotes or various special characters in it. It just doesn't seem like a clean or reliable solution.
I open to anything that will cleanly translate my AngularJS JSON objects into valid Strings, or anything I can do in the ReST method that will allow JSON input without mapping it to a specific object.
Thanks in advance!
Tonya

Grails JSON Converter

I have a method in my main controller that return a string that I want to render as JSON.
So I am importing "import grails.converters.JSON" and calling
myMethod() as JSON
, and it works fine. But when I need to get some details of the json response in my integration test.
So in my integration test I have:
void testfoo() {
def bar = controller.myMethod();
def bar.name; //fails
JSON.parse(bar.toString()).name; // doesn't fail
....
..
}
any idea why I need to convert it to a string and then again to a JSON, since it already a JSON?
The value you get back from your method is a grails.converters.JSON, which is not a directly accessible JSON tree as such, but simply an object that knows how to serialize itself as JSON when required. If you want direct access to the JSON tree structure then you need to tell the grails.converters.JSON object to serialize itself and then pass that JSON to JSON.parse to turn it into a JSONElement (or one of its subclasses, in this case presumably a JSONObject).