I have a code where i get a Json response in array format
{ "data": {
"findAllUsers": {
"pendingUsers": [
{
"userId": "123",
"firstName": "FirstNamemz8",
"lastName": "LastName0Hz",
"status": "Pending"
},
{
"userId": "456",
"firstName": "FirstNameEgl",
"lastName": "LastNameVCC",
"status": "Pending"
}
]
} }}
I need to get the list of userID in list format. below is the code i used which doesnt works. Kindly help me out in this with working code.
package com.deedsing;
import com.deedsing.bean.SnowIncident;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class Test {
public static void main(String[] args) {
String jString="{ \"data\": {\r\n" +
"\"findAllUsers\": {\r\n" +
" \"pendingUsers\": [\r\n" +
" {\r\n" +
" \"userId\": \"123\",\r\n" +
" \"firstName\": \"FirstNamemz8\",\r\n" +
" \"lastName\": \"LastName0Hz\",\r\n" +
" \"status\": \"Pending\"\r\n" +
" },\r\n" +
" {\r\n" +
" \"userId\": \"456\",\r\n" +
" \"firstName\": \"FirstNameEgl\",\r\n" +
" \"lastName\": \"LastNameVCC\",\r\n" +
" \"status\": \"Pending\"\r\n" +
" }\r\n" +
" ]\r\n" +
"} }}";
Gson json = new GsonBuilder().create();
JsonElement elem = new JsonParser().parse(jString);
JsonObject obj = elem.getAsJsonObject();
JsonArray jarray = obj.get("data").getAsJsonObject().get("findAllUsers").getAsJsonObject().get("pendingUsers").getAsJsonArray();
for(int i = 0; i < jarray.size(); i++)
{
JsonElement elem2 = jarray.get(i);
JsonObject obj2 = elem2.getAsJsonObject();
System.out.println("UserID -->" + obj2.get("userId").getAsString());
}
}
}
Related
How to iterate json in java. I wanted iterate elements inside payload, grab the first level and second level key and array value. I have converted the same in python. I'm new to java and wanted convert in java. Any help would be appreciated.
Python Code:
import os
import sys
import json
import datetime
def lambda_handler(event, context):
indata = event['payload']
outputDictionary = []
for i in indata:
for j in indata[i]:
for k in indata[i][j]:
outputDictionary.append(dict(source = i,code=j,version=k))
return outputDictionary
Input :
{
"payload": {
"gtl": {
"435185": [
"2019-11-27T14:34:32.368197Z"
]
},
"ptl": {
"A0947863": [
"2019-11-27T14:34:32.368197Z"
]
},
"mtl": {
"A0947863": [
"2019-11-27T14:34:32.368197Z",
"2021-04-27T06:13:12.841968Z"
]
}
}
}
Expected Output
[
{
"source": "gtl",
"code": "435185",
"version": "2019-11-27T14:34:32.368197Z"
},
{
"source": "ptl",
"code": "A0947863",
"version": "2019-11-27T14:34:32.368197Z"
},
{
"source": "mtl",
"code": "A0947863",
"version": "2019-11-27T14:34:32.368197Z"
},
{
"source": "mtl",
"code": "A0947863",
"version": "2021-04-27T06:13:12.841968Z"
}
]
SOLVED IN JAVA:
Java CODE:
import java.util.Iterator;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class ParseJson {
public static void main(String[] args) {
String inputJson = "{\r\n" +
" \"payload\": {\r\n" +
" \"gtl\": {\r\n" +
" \"435185\": [\r\n" +
" \"2019-11-27T14:34:32.368197Z\"\r\n" +
" ]\r\n" +
" },\r\n" +
" \"ptl\": {\r\n" +
" \"A0947863\": [\r\n" +
" \"2019-11-27T14:34:32.368197Z\"\r\n" +
" ]\r\n" +
" },\r\n" +
" \"mtl\": {\r\n" +
" \"A0947863\": [\r\n" +
" \"2019-11-27T14:34:32.368197Z\",\r\n" +
" \"2021-04-27T06:13:12.841968Z\"\r\n" +
" ]\r\n" +
" }\r\n" +
" }\r\n" +
"}";
final JSONObject inputJSONOBject = new JSONObject(inputJson);
JSONObject jsonChildObject = (JSONObject)inputJSONOBject.get("payload");
Iterator iterator = jsonChildObject.keys();
while (iterator.hasNext()) {
String key = null;
while(iterator.hasNext()){
String source = (String)iterator.next();
JSONObject codeChildObject = jsonChildObject.getJSONObject(source);
Iterator iterator2 = codeChildObject.keys();
while(iterator2.hasNext()){
String code = (String)iterator2.next();
org.json.JSONArray jsonArray = codeChildObject.getJSONArray(code);
for(int i=0;i<jsonArray.length();i++){
System.out.println("Source:" + source);
System.out.println("CODE:" + code);
System.out.println("Version: "+jsonArray.get(i));
}
}
}
}
}
//System.out.println(inputJSONOBject);
}
You have done everything right except for that extra loop for the first iterator. Following is the complete working solution.
class ParseJson {
public static void main(String[] args) throws Exception {
String inputJson = "{\r\n" +
" \"payload\": {\r\n" +
" \"gtl\": {\r\n" +
" \"435185\": [\r\n" +
" \"2019-11-27T14:34:32.368197Z\"\r\n" +
" ]\r\n" +
" },\r\n" +
" \"ptl\": {\r\n" +
" \"A0947863\": [\r\n" +
" \"2019-11-27T14:34:32.368197Z\"\r\n" +
" ]\r\n" +
" },\r\n" +
" \"mtl\": {\r\n" +
" \"A0947863\": [\r\n" +
" \"2019-11-27T14:34:32.368197Z\",\r\n" +
" \"2021-04-27T06:13:12.841968Z\"\r\n" +
" ]\r\n" +
" }\r\n" +
" }\r\n" +
"}";
JSONArray output = convert(inputJson);
System.out.println(output.toString(5));
}
private static JSONArray convert(String inputJson) throws Exception {
final JSONObject inputJSONOBject = new JSONObject(inputJson);
JSONObject jsonChildObject = (JSONObject) inputJSONOBject.get("payload");
JSONArray outputArray = new JSONArray();
Iterator payloadIterator = jsonChildObject.keys();//gtl,ptl,mtl
while (payloadIterator.hasNext()) {
String source = (String) payloadIterator.next(); //gtl
JSONObject codeChildObject = jsonChildObject.getJSONObject(source);
Iterator codeIterator = codeChildObject.keys();//123, 456
while (codeIterator.hasNext()) {
String code = (String) codeIterator.next();//123
org.json.JSONArray jsonArray = codeChildObject.getJSONArray(code);// t1,t2,t3
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = new JSONObject();
object.put("source", source);
object.put("code", code);
object.put("version", jsonArray.get(i)); //t1
outputArray.put(object);
}
}
}
return outputArray;
}
}
I want to get the number of properties in the rowdata element, in the example JSON below:
"rowData": [
{
"_idName": "CONFIG_DATA_ENTITY_MAP.CONFIG_DT_ENTITY_MAP_ID",
"ERROR": null,
"_id": 1,
"ENTITY_TYPE": "BASE_TIMESERIES",
"DATA_TYPE": "Date",
"FIX_THIS": 0,
"ENTITY_NAME": "ASP",
"SOURCE_TABLE_COLUMN": "AS_OF_DATE"
},
{
"_idName": "CONFIG_DATA_ENTITY_MAP.CONFIG_DT_ENTITY_MAP_ID",
"ERROR": null,
"_id": 2,
"ENTITY_TYPE": "BASE_TIMESERIES",
"DATA_TYPE": "String",
"FIX_THIS": 0,
"ENTITY_NAME": "ASP",
"SOURCE_TABLE_COLUMN": "CUSTOMER_ID"
}
]
Have you tried converting into JSONObject and use jsonObject.length()?
Here's the rough code:
public static void main(String[] args) {
String jsonData = "{\"rowData\": [\n" +
" {\n" +
" \"_idName\": \"CONFIG_DATA_ENTITY_MAP.CONFIG_DT_ENTITY_MAP_ID\",\n" +
" \"ERROR\": null,\n" +
" \"_id\": 1,\n" +
" \"ENTITY_TYPE\": \"BASE_TIMESERIES\",\n" +
" \"DATA_TYPE\": \"Date\",\n" +
" \"FIX_THIS\": 0,\n" +
" \"ENTITY_NAME\": \"ASP\",\n" +
" \"SOURCE_TABLE_COLUMN\": \"AS_OF_DATE\"\n" +
" },\n" +
" {\n" +
" \"_idName\": \"CONFIG_DATA_ENTITY_MAP.CONFIG_DT_ENTITY_MAP_ID\",\n" +
" \"ERROR\": null,\n" +
" \"_id\": 2,\n" +
" \"ENTITY_TYPE\": \"BASE_TIMESERIES\",\n" +
" \"DATA_TYPE\": \"String\",\n" +
" \"FIX_THIS\": 0,\n" +
" \"ENTITY_NAME\": \"ASP\",\n" +
" \"SOURCE_TABLE_COLUMN\": \"CUSTOMER_ID\"\n" +
" }\n" +
"]}";
try {
JSONObject jsonObject = new JSONObject(jsonData.replace("\n", ""));
JSONArray jsonArray = jsonObject.getJSONArray("rowData");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject temp = jsonArray.getJSONObject(i);
System.out.println("temp = " + temp.length());
}
} catch (JSONException err){
Log.d("Error", err.toString());
}
}
Convert you JSON to Object. Pass it to your controller and read the size of it
#RequestBody Map<String, Object> objectMap
objectMap.size()
A raw solution without exception handling. I use the library 'org.json' and had to wrap your raw String inside braces to make it json compatible:
final String jsonString = "{\"rowData\": [\n"
+ " {\n"
+ " \"_idName\": \"CONFIG_DATA_ENTITY_MAP.CONFIG_DT_ENTITY_MAP_ID\",\n"
+ " \"ERROR\": null,\n"
+ " \"_id\": 1,\n"
+ " \"ENTITY_TYPE\": \"BASE_TIMESERIES\",\n"
+ " \"DATA_TYPE\": \"Date\",\n"
+ " \"FIX_THIS\": 0,\n"
+ " \"ENTITY_NAME\": \"ASP\",\n"
+ " \"SOURCE_TABLE_COLUMN\": \"AS_OF_DATE\"\n"
+ " },\n"
+ " {\n"
+ " \"_idName\": \"CONFIG_DATA_ENTITY_MAP.CONFIG_DT_ENTITY_MAP_ID\",\n"
+ " \"ERROR\": null,\n"
+ " \"_id\": 2,\n"
+ " \"ENTITY_TYPE\": \"BASE_TIMESERIES\",\n"
+ " \"DATA_TYPE\": \"String\",\n"
+ " \"FIX_THIS\": 0,\n"
+ " \"ENTITY_NAME\": \"ASP\",\n"
+ " \"SOURCE_TABLE_COLUMN\": \"CUSTOMER_ID\"\n"
+ " }\n"
+ "]}";
public int numberOfChildElement(String data, int elementIndex){
JSONObject jsonObject = new JSONObject(data);
JSONArray jsonArray = jsonObject.getJSONArray("rowData");
return jsonArray.getJSONObject(elementIndex).length();
}
So if you call the method 'numberOfChildElement' passing in the raw String and the index of the element you want to get the count of (0 or 1 in your example), you should get the result you want.
package com.example.demo;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.simple.parser.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ColumnDefValidator {
public static void columnDef(JSONObject jsonObjects) {
int templengthColumn = 0;
int templelenghtRow = 0;
try {
JSONArray columnDefsData = jsonObjects.getJSONArray("columnDefs");
JSONArray rowDataDefs = jsonObjects.getJSONArray("rowData");
for (int i = 0; i < columnDefsData.length(); i++) {
JSONObject temp = columnDefsData.getJSONObject(i);
templengthColumn = temp.length();
}
for (int i = 0; i < rowDataDefs.length(); i++) {
JSONObject temp = rowDataDefs.getJSONObject(i);
templelenghtRow = temp.length();
}
System.out.println(templengthColumn);
System.out.println(templelenghtRow);
} catch (JSONException err) {
System.out.println(err.toString());
}
}
public static JSONObject parseJSONFile(String filename) throws JSONException, IOException {
String content = new String(Files.readAllBytes(Paths.get(filename)));
return new JSONObject(content);
}
public static void main(String[] args) throws IOException, JSONException, ParseException {
String filename = "/home/niteshb/WaveProject/working_dir/jsonoutput/aggrid/resp_attribute_report.json";
JSONObject jsonObject = parseJSONFile(filename);
columnDef(jsonObject);
}
}
I'm trying to get the values of Alpha, Beta and Gamma from a nested JSON data file.
I'm trying get the Alpha value using something like this
Object o = new JSONParser().parse(new FileReader(newFile("C:\\Users\\abc\\Documents\\file.json")));
JSONObject jo = (JSONObject) o;
JSONArray resultCode = (JSONArray) jo.get("mkDetails");
JSONObject x = (JSONObject) resultCode.get(0);
x.get("Alpha").toString()
This is the JSON:
{
"metadata": {
"offset": 0,
"psize": 10
},
"svc": [
{
"mNumber": "225",
"markIp": {
"Name": "Ant",
"eDate": "3006-08-01",
"cDate": "9999-12-31"
},
"mkDetails": [
{
"Alpha": "D",
"Beta": "S"
}
],
"mNetDetails": [
{
"Gaama": "213",
"mkTypeCode": "23"
}
]
}
],
"serviceFault": {
"faultType": null,
"faultCode": null,
"message": null
}
}
Here is a possible solution. I'm using Gson lib from google. You can import via maven.
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
Here is the code that parses your JSON.
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public static void parseJson (){
String thisJson ="{\r\n" +
" \"metadata\": {\r\n" +
" \"offset\": 0,\r\n" +
" \"psize\": 10\r\n" +
" },\r\n" +
" \"svc\": [\r\n" +
" {\r\n" +
" \"mNumber\": \"225\",\r\n" +
" \"markIp\": {\r\n" +
" \"Name\": \"Ant\",\r\n" +
" \"eDate\": \"3006-08-01\",\r\n" +
" \"cDate\": \"9999-12-31\"\r\n" +
" },\r\n" +
" \"mkDetails\": [\r\n" +
" {\r\n" +
" \"Alpha\": \"D\",\r\n" +
" \"Beta\": \"S\"\r\n" +
" }\r\n" +
" ],\r\n" +
" \"mNetDetails\": [\r\n" +
" {\r\n" +
" \"Gaama\": \"213\",\r\n" +
" \"mkTypeCode\": \"23\"\r\n" +
" }\r\n" +
" ]\r\n" +
" }\r\n" +
" ],\r\n" +
" \"serviceFault\": {\r\n" +
" \"faultType\": null,\r\n" +
" \"faultCode\": null,\r\n" +
" \"message\": null\r\n" +
" }\r\n" +
"}";
Gson gson = new Gson();
JsonElement jelement = new JsonParser().parse(thisJson);
JsonObject jobject = jelement.getAsJsonObject();
JsonArray jarray = jobject.getAsJsonArray("svc");
jobject = jarray.get(0).getAsJsonObject();
JsonArray netDetailsArr = jobject.getAsJsonArray("mNetDetails");
JsonArray mkDetailsArr = jobject.getAsJsonArray("mkDetails");
jobject = netDetailsArr.get(0).getAsJsonObject();
String gamma = jobject.get("Gaama").getAsString();
System.out.println("gamma==>" + gamma);
jobject = mkDetailsArr.get(0).getAsJsonObject();
String alpha = jobject.get("Alpha").getAsString();
String beta = jobject.get("Beta").getAsString();
System.out.println("alpha ==>" + alpha);
System.out.println("beta ===>"+ beta);
}
console output :
gamma==>213
alpha ==>D
beta ===>S
You can’t just do jo.get("mkDetails"), because jo has no key mkDetails. You have to traverse every level of the tree yourself:
JSONObject root = ...;
JSONArray svc = (JSONArray) root.get("svc");
JSONObject svc0 = (JSONObject) svc.get(0);
JSONObject mkDetails = (JSONObject) svc0.get("mkDetails");
JSONObject mNetDetails = (JSONObject) svc0.get("mNetDetails");
String alpha = (String) mkDetails.get("Alpha");
String beta = (String) mkDetails.get("Beta");
String gamma = (String) mNetDetails.get("Gamma");
I have the following schema:
{
"name": "AgentRecommendationList",
"type": "record",
"fields": [
{
"name": "userid",
"type": "string"
},
{
"name": "friends",
"type": {
"type": "array",
"items": {
"name": "SchoolFriends",
"type": "record",
"fields": [
{
"name": "Name",
"type": "string"
},
{
"name": "phoneNumber",
"type": "string"
},
{
"name": "email",
"type": "string"
}
]
}
}
}
]
}
I'm using GenericRecord, and I want to put in an array of arrays for the SchoolFriends.
val avschema = new RestService(URL).getLatestVersion(name)
val schema = new Schema.Parser().parse(avschema.getSchema)
val record = new GenericData.Record(schema)
I would like to do something like record.put(x)
for that particular schema, you can do it in the following way. I would recommend put your record type SchoolFriends in a different schema, it would make easy to get the schema for the collection elements.
import org.apache.avro.Schema;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericRecord;
import java.util.ArrayList;
import java.util.List;
public class PopulateNestedAvroObjects {
public static void main(String [] args ){
String strSchema = "{\n" +
" \"name\": \"AgentRecommendationList\",\n" +
" \"type\": \"record\",\n" +
" \"fields\": [\n" +
" {\n" +
" \"name\": \"userid\",\n" +
" \"type\": \"string\"\n" +
" },\n" +
" {\n" +
" \"name\": \"friends\",\n" +
" \"type\": {\n" +
" \"type\": \"array\",\n" +
" \"items\": {\n" +
" \"name\": \"SchoolFriends\",\n" +
" \"type\": \"record\",\n" +
" \"fields\": [\n" +
" {\n" +
" \"name\": \"Name\",\n" +
" \"type\": \"string\"\n" +
" },\n" +
" {\n" +
" \"name\": \"phoneNumber\",\n" +
" \"type\": \"string\"\n" +
" },\n" +
" {\n" +
" \"name\": \"email\",\n" +
" \"type\": \"string\"\n" +
" }\n" +
" ]\n" +
" }\n" +
" }\n" +
" }\n" +
" ]\n" +
"}";
Schema schema = new Schema.Parser().parse(strSchema);
GenericRecord record = new GenericData.Record(schema);
record.put("userid", "test user");
Schema childSchema = record.getSchema().getField("friends").schema().getElementType();
List<GenericRecord> friendList = new ArrayList();
GenericRecord friend1 = new GenericData.Record(childSchema);
friend1.put("Name", "1");
friend1.put("phoneNumber", "2");
friend1.put("email", "3");
friendList.add(friend1);
record.put("friends", friendList);
System.out.println(record);
}
}
I have a json array as below:
[
{
"_id": {
"$oid": "57833bf8cb3099a383e8e2af"
},
"Name": "3GBWS",
"Version": "QV3.2",
"Type": "FQGA",
"SerialNO": "L1D73708884",
"Location": "TEXAS"
},
{
"_id": {
"$oid": "5784818bcb30b4918964b50f"
},
"Name": "3GBTW",
"Version": "WN6.0",
"Type": "FQGW",
"SerialNO": "O1143734584",
"Location": "OHIO"
},
{
"_id": {
"$oid": "5784818bcb30b4918964b50f"
},
"Name": "TEXAS",
"Version": "AS1.0",
"Type": "FWQA",
"SerialNO": "DH783708884",
"Location": "NY"
},
{
"_id": {
"$oid": "5784818bcb30b4918964b50f"
},
"Name": "3GLTS",
"Version": "WE9.0",
"Type": "FQGW",
"SerialNO": "L0943708884",
"Location": "TEXAS"
}
]
My aim is to get output as Texas=2 .
Here I need to get the occurrence of "TEXAS" only under the key "Location".
Is there any way to compare the key-value pair in java? I tried with int location = Collections.frequency(json_string, "TEXAS"); , but this wont consider the key "Location".
Please help.
Since you haven't provided your JSON library I'm assuming org.json.
import org.json.JSONArray;
import org.json.JSONObject;
public class Test {
public static void main(String... args) {
String json = "[\r\n" +
" {\r\n" +
" \"_id\": {\r\n" +
" \"$oid\": \"57833bf8cb3099a383e8e2af\"\r\n" +
" },\r\n" +
" \"Name\": \"3GBWS\",\r\n" +
" \"Version\": \"QV3.2\",\r\n" +
" \"Type\": \"FQGA\",\r\n" +
" \"SerialNO\": \"L1D73708884\",\r\n" +
" \"Location\": \"TEXAS\"\r\n" +
" },\r\n" +
" {\r\n" +
" \"_id\": {\r\n" +
" \"$oid\": \"5784818bcb30b4918964b50f\"\r\n" +
" },\r\n" +
" \"Name\": \"3GBTW\",\r\n" +
" \"Version\": \"WN6.0\",\r\n" +
" \"Type\": \"FQGW\",\r\n" +
" \"SerialNO\": \"O1143734584\",\r\n" +
" \"Location\": \"OHIO\"\r\n" +
" },\r\n" +
" {\r\n" +
" \"_id\": {\r\n" +
" \"$oid\": \"5784818bcb30b4918964b50f\"\r\n" +
" },\r\n" +
" \"Name\": \"TEXAS\",\r\n" +
" \"Version\": \"AS1.0\",\r\n" +
" \"Type\": \"FWQA\",\r\n" +
" \"SerialNO\": \"DH783708884\",\r\n" +
" \"Location\": \"NY\"\r\n" +
" },\r\n" +
" {\r\n" +
" \"_id\": {\r\n" +
" \"$oid\": \"5784818bcb30b4918964b50f\"\r\n" +
" },\r\n" +
" \"Name\": \"3GLTS\",\r\n" +
" \"Version\": \"WE9.0\",\r\n" +
" \"Type\": \"FQGW\",\r\n" +
" \"SerialNO\": \"L0943708884\",\r\n" +
" \"Location\": \"TEXAS\"\r\n" +
" }\r\n" +
"]";
JSONArray array = new JSONArray(json);
int count = 0;
for(int i = 0; i < array.length(); i++) {
JSONObject element = array.getJSONObject(i);
String location = element.getString("Location");
if(location.equals("TEXAS")) {
count ++;
}
}
System.out.println("TEXAS=" + count);
}
}
I'd recommend you generate your POJO classes with an online tool (e.g. http://www.jsonschema2pojo.org/) and then you can simply manipulate them anyway you want. For example with a static method:
public static int countLocationOccurrences(List<YourClass> collections, String location) {
int count = 0;
for(YourClass item : collections) {
if (item.getLocation().equals(location)) {
count++;
}
}
return count;
}
First filter some values:
locations = j.map(elem => elem.Location) // j is the array
after this you well have an array with the locations, and you can do with it as you like.