JsonConvert.DeserializeObject - json

I am trying to DeserializeObject but have not idea how to reach the object within the brackets []
dynamic response = null;
response = JsonConvert.DeserializeObject(apiResponseContent);
apiResponseContent =
"CasinoId: " + response.Result.FirstName + "\r\n" +
"PlayerId: " + response.Result.Id
The response which I am trying to parse it:
"{\"Status\":{\"ErrorCode\":0,\"ErrorName\":\"SUCCEED\",\"ErrorMessage\":\"\",\"ReferenceNumber\":\"\"},\"Result\":[{\"FirstName\":Adam,\"Id\":6161999\"}]}"
Would appreciate as answer

I believe you can access fields in the JSON object using a key collection, so response["keynamehere"].
But the best way is to create an object that mimics the objects and fields of your JSON object, and then you can deserialize to that object and it will map the fields. (ie: JsonConvert.DeserializeObject<YOUROBJECTHERE>(apiResponseContent))
Please see some reference links on how to do that in more detail:
http://www.newtonsoft.com/json/help/html/DeserializeObject.htm
Deserializing JSON data to C# using JSON.NET
If you want to get a bit more fancy, you can create your own custom converter:
Deserialize the JSON where the values are field names with JSON.NET

Related

Obtain value in json response

How do i write an expression to obtain the value "lastUpdated" in the below json response data
{"resourceType":"Parameters","parameter":[{"name":"medication","resource":{"resourceType":"Bundle","id":"956ffe6a-08ed-4cb6-82ca-41065a4a9923","meta":{"lastUpdated":"2020-08-24T19:09:18.5649325+00:00",
I have tried this but it does not work:
regex("\"lastUpdated\": \"(.*?)\"").saveAs("lastUpdated")
this also does not work:
jsonPath("$..[?(#.use==\"lastUpdated\")].value").saveAs("lastUpdated"))
Your input is a little cut off but here is what I've got:
myJSONString = '{"resourceType":"Parameters","parameter":[{"name":"medication","resource":{"resourceType":"Bundle","id":"956ffe6a-08ed-4cb6-82ca-41065a4a9923","meta":{"lastUpdated":"2020-08-24T19:09:18.5649325+00:00"}}}]}'
myJSONObject = JSON.parse(myJSONString)
myLastUpdated = myJSONObject.parameter[0].resource.meta.lastUpdated
console.log(myLastUpdated)
Basically you convert it from a json object into a javascript object. Then you can just traverse down the tree to your intended target.

Axis2 JSon Support (Jettison) bad xml conversion

I am using Axis2 1.6.4 to implement REST Json WebServices (https://axis.apache.org/axis2/java/core/docs/json_support.html) and I face an issue when Jettison converts Json object To XML if it does not have a "root" element. Details:
If request is:
{"name":"John","age":30}
Then XML OMElement at server side is:
<name>John</name
So age element is missed
Instead, if request is:
{person:{"name":"John","age":30}}
Then XML OMElement at server side is:
<person><name>John</name><age>30</age></person>
Thanks for your help,
Martí
I've founda work around to overcome this JSON->XML conversion issue. Thanks to this post:How to use Axis2 JSON, I've realized I am able to access input json before converting it to XML, and also to create an OMElement from a json string. So when input is a json request, I wrap it with a json "root" element, and then convert it to XML without losing data.
If it could be useful to someone, below is the source code to get input json string and the source code to convert json string to OMElement
Get input json string and wrap into a root
OMSourcedElement source=(OMSourcedElement )msg;
AbstractJSONDataSource jsonSoucre=(AbstractJSONDataSource)source.getDataSource();
MessageContext msgCtxt= MessageContext.getCurrentMessageContext();
JSONDataSource jsonRequestEnvDS= new JSONDataSource(new StringReader("{\"JSONEnvelope\": " + jsonSoucre.getObject() + " }"), msgCtxt);
OMFactory factory = OMAbstractFactory.getOMFactory();
OMSourcedElement omRequest = factory.createOMElement(jsonRequestEnvDS,null,null);
Create an OMElement from a json string
String jsonString="{...}";
JSONDataSource jsonDS= new JSONDataSource(new StringReader(jsonString),msgCtxt);
factory = OMAbstractFactory.getOMFactory();
OMSourcedElement resonseJson = factory.createOMElement(jsonDS,null,null);
return resonseJson;

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

How do I create a Json Object dynamically?

I want to create a Json object from the below string using Java
{"attributes":{"numvcpus":1,"memsize":3072},"id":"OS Node","type":"image"}
If I know that the string will be what it is , I can create a Json object like this
JsonObject jObj = Json.createObjectBuilder()
.add("attributes",Json.createObjectBuilder()
.add("numvcpus",1)
.add("memsize",3072))
.add("id", "OS node")
.add("type": "image").build();
But the problem here is I don't know how many values will come in the nested json object i.e, the json object which is the value for "attributes" field. There may be additional fields like "disksize": 30, "lcpu": 4 etc . Is there any way to dynamically create Json objects, using for loop, while loop ?

GWT Autobean - how to handle lists?

I have been trying to evaluate GWT Autobean feature to decode/encode JSON object to domain objects for REST calls.
Following the example : http://code.google.com/p/google-web-toolkit/wiki/AutoBean#Quickstart
I was able to convert a singular JSON object to a domain object:
AutoBean<Person> personBean = AutoBeanCodex.decode(factory, Person.class, JsonResources.INSTANCE.json().getText());
where JsonResources.INSTANCE.json() is returning a JSON string.
However, I haven't been successful to convert a list of Person objects from JSON.
It would be helpful, if anyone has an example of this?
Thanks!
Well the only way I can think of is to create a special autobean, which will have List<Person> property. For example:
public interface Result {
void setPersons(List<Person> persons);
List<Person> getPersons();
}
And example json string:
{
persons:[
{"name":"Thomas Broyer"},
{"name":"Colin Alworth"}
]
}
UPDATE:
Workaround when input JSON is an array ( as suggested by persons[0] in comments).E.g. JSON looks like this:
[{"name":"Thomas Broyer"},{"name":"Colin Alworth"}]
And parsing code looks like this:
AutoBeanCodex.decode(factory, Result.class, "{\"persons\": " + json + "}").getPersons();