Create org.json.JSONObject from a class object by using Gson - java

I have the following Java class
public static class LogItem {
public Long timestamp;
public Integer level;
public String topic;
public String type;
public String message;
}
and I want to convert an ArrayList<LogItem> into the following JSON string:
{"logitems":[
{"timestamp":1560924642000, "level":20, "topic":"websocket", "type":"status", "message":"connected (mobile)"},
...
]}`
I would like to do the following:
JSONArray logitems = new JSONArray();
for (DB_LogUtils.LogItem item : items) {
logitems.put(DB_LogUtils.asJSONObject(item)); // <----
}
JSONObject data = new JSONObject();
data.put("logitems", logitems);
webViewFragment.onInjectMessage(data.toString(), null);
where DB_LogUtils.asJSONObject is the following method
public static JSONObject asJSONObject(LogItem item) throws JSONException
{
JSONObject logitem = new JSONObject();
logitem.put("timestamp", item.timestamp);
logitem.put("level", item.level);
logitem.put("topic", item.topic);
logitem.put("type", item.type);
logitem.put("message", item.message);
return logitem;
}
but instead of doing this manually (like logitem.put("timestamp", item.timestamp);) I want to do this with Gson, so that I would end up with something like this
JSONArray logitems = new JSONArray();
for (DB_LogUtils.LogItem item : items) {
logitems.put(new Gson().toJSONObject(item)); // <----
}
JSONObject data = new JSONObject();
data.put("logitems", logitems);
webViewFragment.onInjectMessage(data.toString(), null);
in order to not have to edit the code at multiple points when the LogItem class changes.
But Gson().toJSONObject(...) does not exist, only Gson().toJson(...), which returns a String. I don't want to transition into a String only to then parse it with org.json.JSONObject.
I ended up using a second class
public static class LogItems {
public List<LogItem> logitems = new ArrayList<>();
}
which then let me change the whole code to
webViewFragment.onInjectMessage(new Gson().toJson(items), null);
where items would be of type LogItems.
In this case, creating the extra wrapper class was an overall benefit, but I'd still want to know how I can create such a JSONObject from a class by using Gson.

As far as i know it could be not possible without using for loop to iterate json string into array and store into map with same key.
But you can achieve your solution instead of passing dto pass the list of items into gson object as follow.
List<Object> list = new ArrayList<Object>();
list.add("1560924642000");
list.add(20);
list.add("websocket");
list.add("status");
list.add("connected (mobile)");
Gson gson = new Gson();
Map mp = new HashMap();
mp.put("ietams", list);
String json = gson.toJson(mp);
System.out.println(json);
output will be
{"logitems":["1560924642000",20,"websocket","status","connected (mobile)"]}
Hope this will help !

Related

How to convert a json string to an object

here is my pojo
public class Data{
List<Object> objects;
String owneruid;
}
if the out put is pure json like this
{"object":[{"p1":100,"p2":"name","p3":"sfa0","p4":300}],"owneruid":"owneruid"}
then iam able to convert with no worries but
here is my output
{
"object":"[{\"p1\":32,\"p3\":470,\"p3\":\"213\",\"p4\":\"name\"}]",
"owneruid":"6697729776330393738"
}
im converting a json string to string because to store in my db as it does not accept json so when i query returns like above so every time i need to fetch the value and convert it to json object and put it in list and display. can you suggest me a better approach.
And when i try to convert a list of custom classes to json using GSON
ArrayList<Object> list=new ArrayList<>();
Object object=new Object();
object.setP1(3);
object.setP2(4);
list.add(object);
Gson gson=new Gson();
String json = gson.toJson(list);
Required:
{"object":[{"p1":100,"p2":"name","p2":"sfa0","p4":300}],"owneruid":"owneruid"}
buts it ends like this
{"object":"[{\"p1\":313,\"p2\":470,\"p3\":\"1521739327417\",\"p4\":\"name\"}]","owneruid":"6697729776330393738"}
You have to use any json frameworks. E.g. Jackson or Gson. As alternative you could do smth. like this. Just evaluate JavaScript.
public static void main(String... args) throws ScriptException {
ScriptEngine js = new ScriptEngineManager().getEngineByName("javascript");
Object obj = js.eval("[{\"width\":313,\"height\":470,\"mediauid\":\"1521739327417\",\"mediatype\":\"image\"}]");
// res is either List<Object> or Map<String, Object>
Object res = convertIntoJavaObject(obj);
}
private static Object convertIntoJavaObject(Object obj) {
if (!(obj instanceof ScriptObjectMirror))
return obj;
ScriptObjectMirror mirror = (ScriptObjectMirror)obj;
if (mirror.isArray())
return mirror.entrySet().stream()
.map(entry -> convertIntoJavaObject(entry.getValue()))
.collect(Collectors.toList());
Map<String, Object> map = new HashMap<>();
mirror.entrySet().forEach((key, value) -> map.put(key, convertIntoJavaObject(value)));
return map;
}
You can use the below code snippet as it seems fit for your case.
ObjectMapper can be found with Jackson framework. inputJson is the JSON string you have mentioned.
ObjectMapper mapper = new ObjectMapper();
Object mediaMetaDataObj = mapper.readValue( inputJson, Object.class );
Hope this helps.

Gson can't deserialize multiple type List

I have a class which holds other objects in an ArrayList:
class Program {
#Expose
private List<BaseData> dataList;
}
And I have other classes:
class BaseData {
#Expose
String name;
}
class Data extends BaseData {
#Expose
String description;
}
class DataA extends Data{
#Expose
String a;
}
class DataB extends Data{
#Expose
String b;
}
When I would like to serialize it:
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
Log.d(TAG, gson.toJson(myProgram));
I can see only the keys which I have in BaseData. My list in my Program object contains DataA, DataB and Data objects too.
How can I fix this?
Update:
So my program work like this: it does stuff and fills the Program's list with data. Than I save it: I use Gson to turn the Program to a json string. I use Shared Preferences.
Than when I open up the app again, it loads the previously saved json string. I Log.d it, and everything is cool.
Than
I would like to create a Program object from that json.
Gson gson = new Gson();
instance = gson.fromJson(savedJson, Program.class);
And after I serialize it again with Gson happens what I wrote above. So it seems that it only creates BaseData objects from the json.
I found the Solution.
Btw. It feels like a bit "brute force" method.
Gson gson = new Gson();
JSONObject progJsonObj = new JSONObject(json);
progJsonObj.clearDataList();
JSONArray dataList= reader.getJSONArray("dataList");
Program program = gson.fromJson(progJsonObj.toString());
for (int i = 0; i < dataList.length(); i++) {
JSONObject blockData = blocksInProgram.getJSONObject(i);
// Added new class variable of the base class
String type = blockData.getString("dataType");
if (type.equals("data_a")) {
DataA d = gson.fromJson(blockData.toString(), DataA.class);
program.addData(d);
} else if (type.equals("data_b")){
DataB d = gson.fromJson(blockData.toString(), DataB.class);
program.addData(d);
}
}

Parsing JSON Object with no identifier with Jackson

I am getting JSON from a web service, the JSON response I'm getting is:
{
"response":"itemList",
"items":[
"0300300000",
"0522400317",
"1224200035",
"1224200037",
"1547409999"
]
}
I am looking to get each id within the items array. The problem is I'm unsure how to parse this with Jackson when there are no identifiers for the id in the items array. My understanding is I could have an item class with a variable id and #JsonProperty ("id"), but I don't know how to proceed. I need to display these ids in a list (which I can do no problem once I have the data.
Could someone please point me in the right direction.
Thank you.
You could deserialize into something like
public class MyData {
public String response;
public List<String> items;
}
(this will also work if you have private fields with public set methods). Or if you don't mind having jackson-specific annotations in your data classes, you can leave them as non-public and annotate them:
public class MyData {
#JsonProperty
String response;
#JsonProperty
List<String> items;
}
either way, use this to parse:
import com.fasterxml.jackson.databind.ObjectMapper;
//...
MyData data=new ObjectMapper().readValue(jsonStringFromWebService, MyData.class);
You can Convert the JSON String to JSON object, and identify the array and get the IDs..
String josn = "{\"response\":\"itemList\", \"items\":[\"0300300000\",\"0522400317\",\"1224200035\",\"1224200037\",\"1547409999\"]}";
JSONObject jsonObject = new org.json.JSONObject(josn);
JSONArray itemsArray = jsonObject.getJSONArray("items");
System.out.println("Item - 1 =" + itemsArray.getString(0));
class Something {
public String response;
#JsonCreator
public Something(#JsonProperty("response") String response) {
this.response=response;
}
public List<String> items= new ArrayList<String>();
public List<String> addItem(String item) {
items.add(item);
return items;
}
}
and then:
public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
String json = "{\"response\":\"itemList\",\"items\":[\"0300300000\",\"0522400317\"]}";
ObjectMapper mapper = new ObjectMapper();
mapper.readValue(json, Something.class);
}
I think so, you want this :
ArrayList<String> notifArray=new ArrayList<String>();
JSONObject jsonObj= new JSONObject (resultLine);
JSONArray jArray = jsonObj.getJSONArray("items");
for (int i = 0; i < jArray.length(); i++) {
String str = jArray.getString(i);
notifArray.add(str);
}

How to parse json data using in java

I am getting this data from server how to parse this data in java .
LabelField jsonResult = new LabelField(connectJson.response);
"[{\"screen_refresh_interval\":4,\"station_list_last_update\":\"update4\"},{\"screen_refresh_interval\":4,\"station_list_last_update\":\"update4\"},{\"screen_refresh_interval\":4,\"station_list_last_update\":\"update4\"},{\"screen_refresh_interval\":4,\"station_list_last_update\":\"update4\"},{\"screen_refresh_interval\":4,\"station_list_last_update\":\"update4\"}]"
I am getting response in jsonResult variable
You can use libraries like Jackson to do the same. There is also Google's GSON which will help you do the same. See this example
Take a look at the JSONParser Object in this Tutorial
If you are using Eclipse plugin than may JSON library included in you SDK.
Use below code to parse your JSON string got from the server.
String test = "[{\"screen_refresh_interval\":4,\"station_list_last_update\":\"update4\"},{\"screen_refresh_interval\":4,\"station_list_last_update\":\"update4\"},{\"screen_refresh_interval\":4,\"station_list_last_update\":\"update4\"},{\"screen_refresh_interval\":4,\"station_list_last_update\":\"update4\"},{\"screen_refresh_interval\":4,\"station_list_last_update\":\"update4\"}]";
JSONArray array = new JSONArray(test);
JSONObject obj = (JSONObject) array.get(0);
Your String look like you got JSON Array from the server.
First convert your Json string to JSON Array by
JSONArray array = new JSONArray(Your JSON String);
Each element in array represent JSON Object.You can read JSON Object by
JSONObject obj = (JSONObject) array.get(Index);
You can read parameter from Object to any String variable by :
String valueStr = obj.getString("screen_refresh_interval");
May this help you.
Design a class (viz CustomClass) first with screen_refresh_interval and station_list_last_update as properties. And Make a collection class for CustomClass
I'm using Gson as deserializer. Other libraries are also available.
public class Container {
private CustomClass[] classes;
public CustomClass[] getClasses() {
return classes;
}
public void setClasses(CustomClass[] classes) {
this.classes = classes;
}
}
public class CustomClass {
private String screen_refresh_interval;
private String station_list_last_update;
public String getScreen_refresh_interval() {
return screen_refresh_interval;
}
public void setScreen_refresh_interval(String screen_refresh_interval) {
this.screen_refresh_interval = screen_refresh_interval;
}
public String getStation_list_last_update() {
return station_list_last_update;
}
public void setStation_list_last_update(String station_list_last_update) {
this.station_list_last_update = station_list_last_update;
}
}
Gson gson = new Gson();
Container customClassCollection = gson.fromJson(jsonResult, Container.class);

Java with GSON - deserialize only the values into an ArrayList of a JSON string

I have this structure of my JSON response string:
{
"1":{
"data1":"1","data2":"test1", ...
},
"2":{
"data1":"6","data2":"test2", ...
},
...
}
And I want to get the values to put into an ArrayList<MyItem>. I use GSON and normally I can do it in this way:
ArrayList<MyItem> items =
gson.fromJson(jsonString, new TypeToken<ArrayList<MyItem>>() {}.getType());
The problem is, that it does not work, because my JSON String has numbers as keys, but I only want to get the values to put into the ArrayList (unfortunately, the JSON string can not be changed by myself). How can I do this efficiently?
I'd probably deserialize the JSON into a java.util.Map, get the values from the Map as a Collection using the Map.values() method, and then create a new ArrayList using the constructor that takes a Collection.
Write a custom deserializer.
class MyItem
{
String data1;
String data2;
// ...
}
class MyJSONList extends ArrayList<MyItem> {}
class MyDeserializer implements JsonDeserializer<MyJSONList>
{
public MyJSONList deserialize(JsonElement je, Type type, JsonDeserializationContext jdc)
throws JsonParseException
{
MyJSONList list = new MyJSONList();
for (Entry<String, JsonElement> e : je.getAsJsonObject().entrySet())
{
list.add((MyItem)jdc.deserialize(e.getValue(), MyItem.class));
}
return list;
}
}
Example:
String json = "{\"1\":{\"data1\":\"1\",\"data2\":\"test1\"},\"2\":{\"data1\":\"6\",\"data2\":\"test2\"}}";
Gson g = new GsonBuilder()
.registerTypeAdapter(MyJSONList.class, new MyDeserializer())
.create();
MyJSONList l = g.fromJson(json, MyJSONList.class);
for (MyItem i : l)
{
System.out.println(i.data2);
}
Output:
test1test2

Categories