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.
Related
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"
I'm trying to get JSON on android from my own rest server on localhost using okHttp like this:
JSON
{
"status": true,
"data": [
{
"id": "1",
"title": "Jadwal Catin 2021",
"description": "bismillah"
},
{
"id": "2",
"title": "Jadwal Vaksin Covid Lansia",
"description": "Tanggal 16-Juli-2021 di puskesmas perwira sudah bisa vaksin covi-19 untuk lansia"
}
]
}
Data Class
class Placeholder {
var userId: Int? = null
var id: Int? = null
var title: String? = null
#SerializedName("description")
var body: String? = null
}
Into Recycleview
override fun onResponse(call: okhttp3.Call, response: okhttp3.Response) {
val body = response.body!!.string()
var gson = GsonBuilder().create()
var result = gson.fromJson(body, Array<Placeholder>::class.java).toList()
runOnUiThread {
beritaAdapter.setData(result)
}
Any ideas how should I fix it?
The JSON you show here is not just an array of Placeholder, it's a JSON object ({ ... }), which itself contains 2 properties status and data. And data is an array of objects that partially match your Placeholder class.
You can represent the overall JSON by the following class:
class PlaceholdersResponse {
var status: Boolean
var data: List<Placeholder>
}
And you can access your data array this way:
var result = gson.fromJson(body, PlaceholdersResponse::class.java).data.toList()
I am having a JSON Object as below:
{
"winame": "123",
"val": "[
{
"gurName": "sds",
"gurType": "",
"crNo": "",
"crissueDate": "",
"dob": "",
"gender": "",
"address": "",
"maritialStatus": "",
"cache": ""
}
]"
}
In which first key is value and second key contains the values of some Java Object type. How to parse the value of 'winame' and 'val' into that java Object.
You can parse JSON with any number of keys.
JSONObject obj = new JSONObject("xyz");
String winame= obj.getJSONObject("winame");
JSONArray arr = obj.getJSONArray("val");
for (int i = 0; i < arr.length(); i++)
{
String gurName = arr.getJSONObject(i).getString("gurName");
String gurType = arr.getJSONObject(i).getString("gurType");
String crNo = arr.getJSONObject(i).getString("crNo");
String crissueDate = arr.getJSONObject(i).getString("crissueDate");
String dob = arr.getJSONObject(i).getString("dob");
String gender = arr.getJSONObject(i).getString("gender");
String address = arr.getJSONObject(i).getString("address");
String maritialStatus = arr.getJSONObject(i).getString("maritialStatus");
String cache = arr.getJSONObject(i).getString("cache");
}
I want to do an API call using HttpUrlConnection for POST as the JSON content looks like this
To POST I need to pass key as id and value as 1234.
{
"message": "Success",
"constituency": [{
"id": "1",
"constituency_name": "abc"
}, {
"id": "2",
"constituency_name": "def"
}]
}
I need to fetch this array of strings. How do I do this?
jsonObj = new JSONObject(response);
jsonData = jsonObj.optJSONObject("data");
JSONArray arrJson = jsonData.getJSONArray("numbers");
String[] arr = new String[arrJson.length()];
for(int i = 0; i < arrJson.length(); i++)
arr[i] = arrJson.getString(i);
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
}