Json.Net: Trimming an object to save web traffic - json

I have a very complex JSON returning from an API. I need to pass only the "first level" to the client side, without all the nested objects contained in it.
For example:
{
"name": "David",
"age": 5,
"school": {
"name": "Highschool",
"location": "AZ"
}
}
I'd like to pass to the client side only name & age, not "school".
Is there a simple way to do that?

You could parse the JSON into a JObject then copy all the "simple" properties (i.e. those that are not objects and arrays) to a new JObject. Then get the new JSON from the copy.
For example:
string json = #"
{
""name"": ""David"",
""age"": 5,
""school"": {
""name"": ""Highschool"",
""location"": ""AZ""
}
}";
JObject origObj = JObject.Parse(json);
JObject copyObj = new JObject();
foreach (JProperty prop in origObj.Properties())
{
if (prop.Value.Type != JTokenType.Object &&
prop.Value.Type != JTokenType.Array)
{
copyObj.Add(prop.Name, prop.Value);
}
}
json = copyObj.ToString();
Console.WriteLine(json);
The above will output the following:
{
"name": "David",
"age": 5
}

Related

Groovy Modifying Json

I'm trying to modify a json which I'm reading from a file:
String response = new File("response.json").text
here is what response looks like:
{
"TerminatingInstances": [
{
"InstanceId": "id",
"CurrentState": {
"Code": 32,
"Name": "shutting-down"
},
"PreviousState": {
"Code": 16,
"Name": "running"
}
}
]
}
To modify it I did as follows:
def slurped = new JsonSlurper().parseText(response)
def builder = new JsonBuilder(slurped)
builder.content.TerminatingInstances.InstanceId = "id-updated"
but I get argument type mismatch error, not sure why.
That's because it's an array of instances inside TerminatingInstances
You can either set all of them to the new id with *.:
builder.content.TerminatingInstances*.InstanceId = "id-updated"
Or set just the first one with
builder.content.TerminatingInstances[0].InstanceId = "id-updated"

JSON Array Parsing Kafka

I have the following setup:
A Rest endpoint to accept JSON POST request:
I am parsing the request and sending it as a String over Kafka.
But getting parsing errors
A Rest endpoint to accept JSON POST request:
[ { "Name": "Jack", "Id": "314", "Gender": "M" } , { "Name": "John", "Id": "451", "Gender": "M" }, { "Name": "Rita", "Id": "501", "Gender": "F" } ]
I am parsing the request as follows
#RequestMapping(method = RequestMethod.POST, value = "/record")
#ResponseBody
public String process(#RequestBody Map<String, Object>[] payload) throws
Exception {
String str = Arrays.toString(payload)
KafkaProd.toTopic(str);
System.out.println("Payload: " +str);
return "Record Processed";
}
str = Arrays.toString(payload) is changing it into the following format
[ { Name = Jack , Id = 314, Gender = M } , { Name = John, Id = 451,
Gender = M }, { Name = Rita, Id = 501, Gender = F } ]
When I'm trying to parse this string back into json array using json-s
imple :
JSONArray jsonArray = new JSONArray(record.value());
for (int i = 0; i < jsonArray.length(); i++) {
System.out.println("Json Objects : "
+jsonArray.getJSONObject(i).toString());
}
I am getting JSON Parsing error, since the record.value() is not a valid json array
Option 1. How do I convert this to a valid json array?
Option 2. How do I send the json array in a proper format through kafka?
Which of these options do I use?
Instead of String str = Arrays.toString(payload) use a Jackson ObjectMapper to convert the map to a String.

Convert JSON to Gpath result

I want to convert all the JSON key values the Map. Where I need key as gpath result and value as object key value.
Input Json
{
"employees": {
"employee": [{
"id": "1",
"firstName": "Tom",
"lastName": "Cruise",
"photo": "https://pbs.twimg.com/profile_images/735509975649378305/B81JwLT7.jpg"
},
{
"id": "2",
"firstName": "Maria",
"lastName": "Sharapova",
"photo": "https://pbs.twimg.com/profile_images/3424509849/bfa1b9121afc39d1dcdb53cfc423bf12.jpeg"
},
{
"id": "3",
"firstName": "James",
"lastName": "Bond",
"photo": "https://pbs.twimg.com/profile_images/664886718559076352/M00cOLrh.jpg"
}
]
}
}
Output I am expecting,
[employees.employee[0].id:"1",
employees.employee[0].firstName:"tom",
....]
I have tried Groovy jsonSurper() object class but I am unable to find solution to map all keys into gpath.
Any help will be appreciated!
Bit of an odd request... Can't think of why you'd want to do it... but anyway, you'd need to write some logic to recurse through the map generated by JsonSlurper, and collapse the keys...
Assuming your above json is in a String variable json:
def map = new JsonSlurper().parseText(json)
def collapseKey(String prefix, Map result, value) {
if (value instanceof Map) {
value.each { k, v ->
collapseKey("${prefix ? "${prefix}." : ''}$k", result, v)
}
} else if (value instanceof List) {
value.eachWithIndex{ e, idx ->
collapseKey("${prefix}[$idx]", result, e)
}
} else {
result."$prefix" = value
}
result
}
def result = collapseKey("", [:], map)
You could (of course) just parse it into a map and do:
map.employees.employee[0].firstName

Ruby: How to parse json to specific types

I have a JSON that I want to parse in Ruby. Ruby is completely new to me, but I have to work with it :-)
Here is my litte snippet, that should do the parsing:
response = File.read("app/helpers/example_announcement.json")
JSON.parse(response)
this works pretty fine. The only downside is, I do not know the properties at the point where I use it, it is not typesafe. So I created the objects for it
class Announcements
##announcements = Hash # a map key => value where key is string and value is type of Announcement
end
class Announcement
##name = ""
##status = ""
##rewards = Array
end
And this is how the json looks like
{
"announcements": {
"id1" : {
"name": "The Diamond Announcement",
"status": "published",
"reward": [
{
"id": "hardCurrency",
"amount": 100
}
]
},
"id2": {
"name": "The Normal Announcement",
"players": [],
"status": "published",
"reward": []
}
}
}
So I tried JSON parsing like this
response = File.read("app/helpers/example_announcement.json")
JSON.parse(response, Announcements)
But this is not how it works^^can anybody help me with this?

How to get array number with groovy script in SoapUI?

I want to assert the value of a property in Json response with the use of Groovy script in SoapUI. I know a value for name but I need to know on which position the id is.
json response example:
{
"names":[
{
"id":1,
"name":"Ted"
},
{
"id":2,
"name":"Ray"
},
{
"id":3,
"name":"Kev"
}
]
}
Let's say I know that there is a name Ray, I want the position and the id (names[1].id)
Here is the script to find the same:
import groovy.json.*
//Using the fixed json to explain how you can retrive the data
//Of couse, you can also use dynamic value that you get
def response = '''{"names": [ { "id": 1, "name": "Ted", }, { "id": 2, "name": "Ray", }, { "id": 3, "name": "Kev", } ]}'''
//Parse the json string and get the names
def names = new JsonSlurper().parseText(response).names
//retrive the id value when name is Ray
def rayId = names.find{it.name == 'Ray'}.id
log.info "Id of Ray is : ${rayId}"
//Another way to get both position and id
names.eachWithIndex { element, index ->
if (element.name == 'Ray') {
log.info "Position : $index, And Id is : ${element.id}"
}
}
You can see here the output