Inner object(ArrayList) is not converting to JSON String? - java

I am facing issue in converting the nested list object to JSON.I am using object mapper and it is only converting the starting values and after that there is one arraylist inside it and it is not going through that list.
I have tried some basic iteration using JsonNode root = mapper.valueToTree(obj)so that i can iterate through the inner arraylist but i am not getting the result.I am new to this parsing conversion.
code snippet--
public class JsonUtils {
public static <T> String toJsonString(final T obj) throws IOException {
final ObjectMapper mapper = new ObjectMapper();
String jsonString = null;
try {
//JsonNode root = mapper.valueToTree(obj);
jsonString = mapper.writeValueAsString(obj);
} catch (final JsonProcessingException e) {
throw e;
} catch (IOException e) {
throw e;
}
return jsonString;
}
public static <T> String toJsonString(final List<T> lstObject) throws JSONException, IOException {
final JSONArray jsonArray = new JSONArray();
for (final T object : lstObject) {
final String json = JsonUtils.toJsonString(object);
final JSONObject jsonObj = new JSONObject(json);
jsonArray.put(jsonObj);
}
return jsonArray.toString();
}
}
So here is the result which i am getting -
[2, [{"geoMarketId":1,"geoname":"AP","geoId":1,"checked":false},
{"geoMarketId":7,"geoname":"EP","geoId":2,"checked":false},
{"geoMarketId":16,"geoname":"Japan","geoId":3,"checked":true},
{"geoMarketId":18,"geoname":"LA","geoId":4,"checked":true},
{"geoMarketId":22,"geoname":"MEA","geoId":5,"checked":true},
{"geoMarketId":24,"geoname":"NA","geoId":6,"checked":false}]]
Actual Result which should come-
{"geoMarketId":1,"geoname":"AP","geoId":1,"checked":false,
marketName:{"marketname":JP,"marketname":"AP","marketname":MP}}
My json conversion is ignoring this inner list in the same index.
Is there any way my json class can iterate and also convert that innerlist to JSON?

Related

Convert JSON string to json objects

I have a json string returning:
[{"TRAIN_JOURNEY_STAFF[],"ID":15,"EMAIL_ADDRESS":"jk#connectedrail.com","PASSWORD":"test","FIRST_NAME":"Joe","LAST_NAME":"Kevin","DATE_OF_BIRTH":"1996-04-20T00:00:00","GENDER":"Male","STAFF_ROLE":"Conductor","PHOTO":null},{new record..}]
There are several records here, I can't find a way to convert this json string to individual objects. I'm using the following to read in the data:
StringBuffer response;
try (BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()))) {
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
}
System.out.print(response.toString());
}
I've tried the simple json libary but the parser mixes up the string, Which is not ideal as I need to output the data to rows object by object to jtables.
Any help would be appreciated.
Solved it with the below with GSON. Many thanks everyone!
JsonElement jelement = new JsonParser().parse(response.toString());
JsonArray jarray = jelement.getAsJsonArray();
JsonObject jobject = jarray.get(0).getAsJsonObject();
System.out.println(jobject.get("FIRST_NAME"));
You can use something like this:
public class ObjectSerializer {
private static ObjectMapper objectMapper;
#Autowired
public ObjectSerializer(ObjectMapper objectMapper) {
ObjectSerializer.objectMapper = objectMapper;
}
public static <T> T getObject(Object obj, Class<T> class1) {
String jsonObj = "";
T userDto = null;
try {
jsonObj = objectMapper.writeValueAsString(obj);
userDto = (T) objectMapper.readValue(jsonObj, class1);
System.out.println(jsonObj);
} catch (JsonProcessingException jpe) {
} catch (IOException e) {
e.printStackTrace();
}
return userDto;
}
Pass your JSON Object to this method alogn with class name and it will set the JSON data to that respective class.
Note:
Class must have the same variables as in the JSON that you want to map with it.
Using org.json library:
JSONObject jsonObj = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
see this
You can use Jackson to convert JSON to an object.Include the dependency :
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.3</version>
</dependency>
Then make a POJO class to store the JSON .The pojo class should reflect the json string structure and should have appropriate fields to map the values(Here in sample code Staff.class is a pojo class).Then, by using ObjectMapper class you can convert the JSON string to a java object as follows :
StringBuffer response;
try (BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()))) {
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
}
System.out.print(response.toString());
ObjectMapper mapper = new ObjectMapper();
//JSON from file to Object
Staff obj = mapper.readValue(new File("c:\\file.json"), Staff.class);
//JSON from String to Object
Staff obj = mapper.readValue(response.toString(), Staff.class);
Another simple method to read a JSON string and convert it into an object is :
JSON String:
{
"lastName":"Smith",
"address":{
"streetAddress":"21 2nd Street",
"city":"New York",
"state":"NY",
"postalCode":10021
},
"age":25,
"phoneNumbers":[
{
"type":"home", "number":"212 555-1234"
},
{
"type":"fax", "number":"212 555-1234"
}
],
"firstName":"John"
}
public class JSONReadExample
{
public static void main(String[] args) throws Exception
{
// parsing file "JSONExample.json"
Object obj = new JSONParser().parse(new FileReader("JSONExample.json"));
// typecasting obj to JSONObject
JSONObject jo = (JSONObject) obj;
// getting firstName and lastName
String firstName = (String) jo.get("firstName");
String lastName = (String) jo.get("lastName");
System.out.println(firstName);
System.out.println(lastName);
// getting age
long age = (long) jo.get("age");
System.out.println(age);
// getting address
Map address = ((Map)jo.get("address"));
// iterating address Map
Iterator<Map.Entry> itr1 = address.entrySet().iterator();
while (itr1.hasNext()) {
Map.Entry pair = itr1.next();
System.out.println(pair.getKey() + " : " + pair.getValue());
}
// getting phoneNumbers
JSONArray ja = (JSONArray) jo.get("phoneNumbers");
// iterating phoneNumbers
Iterator itr2 = ja.iterator();
while (itr2.hasNext())
{
itr1 = ((Map) itr2.next()).entrySet().iterator();
while (itr1.hasNext()) {
Map.Entry pair = itr1.next();
System.out.println(pair.getKey() + " : " + pair.getValue());
}
}
}
}
For reference:
https://www.geeksforgeeks.org/parse-json-java/
https://www.mkyong.com/java/jackson-2-convert-java-object-to-from-json/
What you have basically is this :
[
{
"TRAIN_JOURNEY_STAFF":[
],
"ID":15,
"EMAIL_ADDRESS":"jk#connectedrail.com",
"PASSWORD":"test",
"FIRST_NAME":"Joe",
"LAST_NAME":"Kevin",
"DATE_OF_BIRTH":"1996-04-20T00:00:00",
"GENDER":"Male",
"STAFF_ROLE":"Conductor",
"PHOTO":null
},
{
}
]
You can use JSON constructor to serialize this array to an Array of JSONObjects.
Try looking for JSONObject and JSONArray classes in Java.
The constructor basically takes the stringified JSON (which you already have).

Unable to parse JSON data using beans in JAVA

Here is my code for the parsing the JSON file and printing too.:
public class JsonpJsonParser implements IparseJson {
public static void main(String[] args) {
IparseJson parser = new JsonpJsonParser();
try (FileInputStream in = new FileInputStream("data.json")) {
List<QueryResultBean1> results = parser.parseJson(in);
for (QueryResultBean1 result : results) {
System.out.println(result.getHeader().getRequest_id());
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public List<QueryResultBean1> parseJson(InputStream in) {
JsonReader reader = Json.createReader(in);
JsonObject json = reader.readObject();
reader.close();
// parse the json object, return something
List<QueryResultBean1> results = new ArrayList<QueryResultBean1>();
JsonArray items = json.getJsonArray("header");
for (JsonValue item : items) {
if (item instanceof JsonObject) {
QueryResultBean1 result = createBean((JsonObject)item);
results.add(result);
}
}
return results;
}
public QueryResultBean1 createBean(JsonObject json) {
QueryResultBean1 bean = new QueryResultBean1();
// you could also change tags to a List
JsonArray array = json.getJsonArray("header");
String[] h1 = new String[array.size()];
for (int i = 0; i < h1.length; i++) {
h1[i] = array.getString(i);
}
bean.setTags(h1);
retrun bean}
Ive tried executing this code for the JSON file:
"header":[
{
"request_id":1547706529870,
"file_name":"Sm-1547706529870.xlsm",
"file_type":"CIR",
"status":"NEW",
"is_end":false
}
GOT THE ERROR AS:
`Exception in thread "main" java.lang.NullPointerExceptionat com.example.webjson.com.webjson.p1.JsonpJsonParser.createBean(JsonpJsonParser.java:60)
NEED HELP TO PARSE THE DATA.JSON FILE IN JAVA
In the code below:
JsonArray array = json.getJsonArray("header");
You are trying to retrieve an JsonArray from String?, you should retrieve the element in array using an index like:
JsonArray array = json.getJsonArray(0);

JSONObject with List to String to JsonNode

I convert JSONObject in string for parse it in JsonNode with jackson but i have a List in my JSONObject and when i parse it with a ObjectMapper i get this :
["{Property1 : value1, Property2 : value2}"]
And i can't call myJsonNodeObject.get(i).get("Property1") this is my problem.
I have tried to cast my List in JSONArray in my JSONObject but don't work.
resultAsJSONObject = new JSONObject();
resultAsJSONObject.put("Label", getMetricStatisticsResult.getLabel());
resultAsJSONObject.put("Datapoints", getMetricStatisticsResult.getDatapoints());
resultAsJSONObject.put("fromDate", fromDate.getTimeInMillis());
resultAsJSONObject.put("toDate", toDate.getTimeInMillis());
resultAsJSONObject.put("error", "");
resultAsString = resultAsJSONObject.toString();
mapper.readValue(resultAsString, MetricsData.class);
Assuming that you have a JSON string which you just want to change. Then you can use Jackson to parse it as a ObjecNode and then modify it. Here is an example:
public class JacksonModifyJson {
static final String JSON = "{\"name\":\"Bob\", \"age\":13}";
public static void main(String[] args) throws IOException {
final ObjectMapper mapper = new ObjectMapper();
final ObjectNode jsonNode = mapper.readValue(JSON, ObjectNode.class);
jsonNode.put("url", "example.com");
System.out.println(mapper.writeValueAsString(jsonNode));
}
}
Output:
{"name":"Bob","age":13,"url":"example.com"}
THis method is really easy and works too
try {
JSONObject jsonObject = new JSONObject(THESTRINGHERE);
String[] names = JSONObject.getNames(jsonObject);
JSONArray jsonArray = jsonObject.toJSONArray(new JSONArray(names));
ArrayList<String> listdata = new ArrayList<String>();
JSONArray jArray = (JSONArray)jsonArray;
if (jArray != null) {
for (int i=0;i<jArray.length();i++){
listdata.add(jArray.get(i).toString());
}
}
// System.out.println(listdata);
} catch (Exception e) {
System.out.println(e.getMessage());
}

Gson deserialize not working properly

I have a jsonarray formatted like this:
String jsonArray = {"myList":[{"code":"01","price":"2,3", "date":"21/12/2014"},{"code":"02","price":"3,4", "date":"26/12/2014"}]}
Mylist class is:
public class MyList {
private String code;
private String price;
private String date;
//..getter and setter
}
My non working "deserializator" is the following:
ObjectMapper objectMapper = new ObjectMapper();
List<MyList> list = new ObjectMapper().readValue(jsonArray, new TypeReference<List<MyList>>() { });
catching the following exception:
org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token
How can I solve that?
Thanks in advance!
Here's my own working solution using Gson:
String jsonArray = {"myList":[{"code":"01","price":"2,3", "date":"21/12/2014"},{"code":"02","price":"3,4", "date":"26/12/2014"}]}
Gson gson = new Gson();
JsonParser parser = new JsonParser();
List<MyList> list = new ArrayList<MyList>();
try {
JsonArray jArray = (JsonArray) parser.parse(jsonArray).getAsJsonObject().get("myList");
for (JsonElement jObj : jArray) {
MyList item = gson.fromJson( jObj , MyList.class);
list.add(item);
}
} catch (Exception e) {
e.printStackTrace();
}
Hope it will be useful for other users!

Access nested JSON object value using java

{
"files": {
"f1.png": {
"intext": "A",
"inval": 0,
"inbinary": false
},
"f2.png": {
"intext": "A",
"inval": 0,
"inbinary": true
}
}
}
How to access value of inval when the f1.png value is not fixed. i.e. the name of file can be anything, its not known so how can I access value for inval field for various files in this JSON using Java?
Please try below code,
import org.json.JSONException;
import org.json.JSONObject;
public static void main(String[] args) {
String jsonString = "{\"files\": {\"f1.png\": {\"intext\": \"A\",\"inval\": 0,\"inbinary\": false}, \"f2.png\": {\"intext\": \"A\",\"inval\": 0,\"inbinary\": true}}}";
try {
JSONObject jsonObject =new JSONObject(jsonString);
JSONObject jsonChildObject = (JSONObject)jsonObject.get("files");
Iterator iterator = jsonChildObject.keys();
String key = null;
while(iterator.hasNext()){
key = (String)iterator.next();
System.out.println("inval value: "+((JSONObject)jsonChildObject.get(key)).get("inval"));
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Hope it solves your issue
Using Jackson and JsonNode, you'd do:
private static final ObjectReader READER = new ObjectMapper()
.getReader;
// blah
// read the node
final JsonNode node = READER.readTree(fromWhatever);
// access the inner "files" member
final JsonNode filesNode = node.get("files");
to access the inner object.
Then to walk the filesNode object you'd do:
final Iterator<Map.Entry<String, JsonNode>> iterator = filesNode.fields();
Map.Entry<String, JsonNode> entry;
while (iterator.hasNext()) {
entry = iterator.next();
// the "inval" field is entry.getValue().get("inval")
}
If you can use this project this becomes more simple:
// or .fromFile(), .fromReader(), others
final JsonNode node = JsonLoader.fromString(whatever);
final Map<String, JsonNode> map = JacksonUtils.nodeToMap(node.get("files"));
// walk the map
You can use JsonPath library to access child elements.
https://github.com/json-path/JsonPath
It can be as simple as
List<String> names = JsonPath.read(json, "$.files.*);
With some modifications.
You can use ObjectMapper.
First create a class Image.
import lombok.Data;
#Data
public class Image {
private String intext;
private Integer inval;
private Boolean inbinary;
}
and convert to Map
final ObjectMapper objectMapper = new ObjectMapper();
final String jsonString =
"{\"files\": {\"f1.png\": {\"intext\": \"A\",\"inval\": 0,\"inbinary\": false}, \"f2.png\": {\"intext\": \"A\",\"inval\": 0,\"inbinary\": true}}}";
final Map<String, Map<String, Image>> output =
objectMapper.readValue(
jsonString, new TypeReference<Map<String, Map<String, Image>>>() {});
Thanks.
for nested array type,
{
"combo": [
{"field":"divisions"},
{"field":"lob"}
]
}
below code will help.
Iterator<?> keys = jsnObj.keys();
while(keys.hasNext()) {
String key = (String) keys.next();
JSONArray list = (JSONArray) jsnObj.get(key);
if(list==null || list.length()==0)
return null;
List<String> comboList = new ArrayList<String>();
for(int i=0;i<list.length();i++){
JSONObject jsonObject = (JSONObject)list.get(i);
if(jsonObject==null)
continue;
comboList.add((String)jsonObject.get("fields"));
}
}

Categories

Resources