I have a dynamic web project where in my jsp page, on clicking a form, it retrieves the data from elasticsearch and displays in the UI in proper json format as Key:value pair.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String start = request.getParameter("start");
String end = request.getParameter("end");
String line1;
StringBuffer jsonString1 = new StringBuffer();
try {
URL url1 = new URL("http://localhost:9200/indexname/_search?filter_path=hits.hits._source&pretty=1&size=100000");
String payload1 = "{\"query\":{\"filtered\":{\"filter\":{\"range\":{\"Date\":{\"lte\":\""+end+"\",\"gte\":\""+start+"\"}}}}},\"_source\":{\"include\":[\"ID\",\"Name\",\"Status\",\"Date\"]}}";
HttpURLConnection connection1 = (HttpURLConnection) url1.openConnection();
connection1.setDoInput(true);
connection1.setDoOutput(true);
connection1.setRequestMethod("POST");
connection1.setRequestProperty("Accept", "application/json");
connection1.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
OutputStreamWriter writer1 = new OutputStreamWriter(connection1.getOutputStream(), "UTF-8");
writer1.write(payload1);
writer1.close();
BufferedReader br1 = new BufferedReader(new InputStreamReader(connection1.getInputStream()));
while ((line1 = br1.readLine()) != null) {
jsonString1.append(line1);
}
br1.close();
file1.close();
connection1.disconnect();
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
response.setContentType("application/json");
// JSONObject jsonObj = new JSONObject(jsonString1.toString()); //JSONObject cannot be resolved to a type error is getting displayed.
//System.out.println("---------------------------");
// System.out.println(jsonObj);
PrintWriter out = response.getWriter();
out.print(jsonString1); //Here instead of String buffer I want to send a json object or an arraylist which outputs just the key value pair by removing all unwanted characters.
out.flush();
out.close();
}
In m HTML, on performing a Submit operation, it displays something like this :
{ "hits" : { "hits" : [ { "_source":{"ID":"123","Status":"false","Name":"ABC_123","Date":"2010-08-16T11:07:48"} }, { "_source":{"ID":"124","Status":"false","Name":"ABC_678","Date":"2010-08-16T12:00:12"} }, { "_source":{"ID":"125","Status":"true","Name":"FGH_122","Date":"2010-08-16T12:01:48"} }, { "_source":{"ID":"126","Status":"false","Name":"TYT_333","Date":"2010-08-16T12:06:48"} }, { "_source":{"ID":"127","Status":"false","Name":"CVF_230","Date":"2010-08-16T12:07:18"} }, { "_source":{"ID":"128","Status":"true","Name":"AWE_101","Date":"2010-08-16T12:03:48"} }, { "_source":{"ID":"129","Status":"true","Name":"WEC_299","Date":"2010-08-16T12:07:29"} } ] }}
Instead, I want to display in my UI some alert box or something like that where it displays
{"ID":"123","Status":"false","Name":"ABC_123","Date":"2010-08-16T11:07:48"},
{"ID":"124","Status":"false","Name":"ABC_678","Date":"2010-08-16T12:00:12"},
{"ID":"125","Status":"true","Name":"FGH_122","Date":"2010-08-16T12:01:48"}
etc....
Any idea on how I can achieve this? Please advice. Thanks.
Do a classic iteration of your json string, before PrintWriter step
String jsonString1 = "{ \"hits\": { \"hits\": [{ \"_source\": { \"ID\": \"123\", \"Status\": \"false\", \"Name\": \"ABC_123\", \"Date\": \"2010-08-16T11:07:48\" } }, { \"_source\": { \"ID\": \"124\", \"Status\": \"false\", \"Name\": \"ABC_678\", \"Date\": \"2010-08-16T12:00:12\" } }, { \"_source\": { \"ID\": \"125\", \"Status\": \"true\", \"Name\": \"FGH_122\", \"Date\": \"2010-08-16T12:01:48\" } }, { \"_source\": { \"ID\": \"126\", \"Status\": \"false\", \"Name\": \"TYT_333\", \"Date\": \"2010-08-16T12:06:48\" } }, { \"_source\": { \"ID\": \"127\", \"Status\": \"false\", \"Name\": \"CVF_230\", \"Date\": \"2010-08-16T12:07:18\" } }, { \"_source\": { \"ID\": \"128\", \"Status\": \"true\", \"Name\": \"AWE_101\", \"Date\": \"2010-08-16T12:03:48\" } }, { \"_source\": { \"ID\": \"129\", \"Status\": \"true\", \"Name\": \"WEC_299\", \"Date\": \"2010-08-16T12:07:29\" } }] }}";
JSONObject jsonObj = new JSONObject(jsonString1);
JSONObject c = jsonObj.getJSONObject("hits");
JSONArray c1 = c.getJSONArray("hits");
// Iterate hits array
for (int i = 0 ; i < c1.length(); i++) {
JSONObject jObject = c1.getJSONObject(i);
System.out.println(jObject.get("_source"));
}
Resultant data looks like,
{"Name":"ABC_123","Status":"false","Date":"2010-08-16T11:07:48","ID":"123"}
{"Name":"ABC_678","Status":"false","Date":"2010-08-16T12:00:12","ID":"124"}
{"Name":"FGH_122","Status":"true","Date":"2010-08-16T12:01:48","ID":"125"}
{"Name":"TYT_333","Status":"false","Date":"2010-08-16T12:06:48","ID":"126"}
{"Name":"CVF_230","Status":"false","Date":"2010-08-16T12:07:18","ID":"127"}
{"Name":"AWE_101","Status":"true","Date":"2010-08-16T12:03:48","ID":"128"}
{"Name":"WEC_299","Status":"true","Date":"2010-08-16T12:07:29","ID":"129"}
As well checkout Demo, It's a client side iteration. If you can able to do it in client side this may help you.
Related
I have the following method that when receiving an xml in a String converts it to objects of type CitiMarketSSAEvent
public CitiMarketSSAEvent convertXmlToObject(String xml){
CitiMarketSSAEvent citiMarket = null;
JAXBContext jaxbContext = JAXBContext.newInstance(CitiMarketSSAEvent.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
StringReader reader = new StringReader(xml);
citiMarket = (CitiMarketSSAEvent) unmarshaller.unmarshal(reader);
return citiMarket;
}
and then I have the following method that converts the objects of that class into a json
public String convertObjectToJson(CitiMarketSSAEvent citiMarketObject) {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setPrettyPrinting();
gsonBuilder.disableHtmlEscaping();
Gson gson = gsonBuilder.create();
return gson.toJson(citiMarketObject, CitiMarketSSAEvent.class);
}
and it paints the json as follows
{
"header":{
"name": "transactionCount",
"version": "2.0",
"code": "1530",
"country": "MX",
"domain": "counts",
"time": "2018-10-11 11:20:34.323 GMT",
},
"body":{
"INPUNT": "I",
"MESSAGE_01": "RSTW",
"MESSAGE_02": "MNXTYP",
"MESSAGE_03": "RSTWERDCV",
"SEND_TIME": "20-NOV-2011 04:53:04 p.m.",
"RCV_ID": "ABGRCV",
"FORMAT0_MONTO": "200,000,300.00",
"FORMATO_MONEDA": "USD",
"CONTROL_01": "MSG1RCVSND",
"CONTROL_02": "MSG2RCVSND",
"CONTROL_03": "MSG3RCVSND",
}
}
but I want to add the "event" key to the json in such a way that I get something like this:
{
"event":{
"header":{
"name": "transactionCount",
"version": "2.0",
"code": "1530",
"country": "MX",
"domain": "counts",
"time": "2018-10-11 11:20:34.323 GMT",
},
"body":{
"INPUNT": "I",
"MESSAGE_01": "RSTW",
"MESSAGE_02": "MNXTYP",
"MESSAGE_03": "RSTWERDCV",
"SEND_TIME": "20-NOV-2011 04:53:04 p.m.",
"RCV_ID": "ABGRCV",
"FORMAT0_MONTO": "200,000,300.00",
"FORMATO_MONEDA": "USD",
"CONTROL_01": "MSG1RCVSND",
"CONTROL_02": "MSG2RCVSND",
"CONTROL_03": "MSG3RCVSND",
}
}
}
and then I modified my method as follows using JSONObject
public String convertObjectToJson(CitiMarketSSAEvent citiMarketObject) {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setPrettyPrinting();
gsonBuilder.disableHtmlEscaping();
JSONObject jsonObj = new JSONObject();
jsonObj.put("event",citiMarketObject);
Gson gson = gsonBuilder.create();
return gson.toJson(jsonObj, JSONObject.class);
}
and it throws me the json but the key "nameValuePairs" was added, how can it be removed? Or how else can I do it to just add the "event" key?
{
"nameValuePairs":{
"event":{
"header":{
"name": "transactionCount",
"version": "2.0",
"code": "1530",
"country": "MX",
"domain": "counts",
"time": "2018-10-11 11:20:34.323 GMT",
},
"body":{
"INPUNT": "I",
"MESSAGE_01": "RSTW",
"MESSAGE_02": "MNXTYP",
"MESSAGE_03": "RSTWERDCV",
"SEND_TIME": "20-NOV-2011 04:53:04 p.m.",
"RCV_ID": "ABGRCV",
"FORMAT0_MONTO": "200,000,300.00",
"FORMATO_MONEDA": "USD",
"CONTROL_01": "MSG1RCVSND",
"CONTROL_02": "MSG2RCVSND",
"CONTROL_03": "MSG3RCVSND",
}
}
}
}
Try this code, it is supposed to do what you need.
package com;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.LinkedHashMap;
public class Main {
public static void main(String[] args) throws JsonProcessingException {
String json = "{\n" +
" \"header\":{\n" +
" \"name\": \"transactionCount\",\n" +
" \"version\": \"2.0\",\n" +
" \"code\": \"1530\",\n" +
" \"country\": \"MX\",\n" +
" \"domain\": \"counts\",\n" +
" \"time\": \"2018-10-11 11:20:34.323 GMT\"\n" +
" },\n" +
" \"body\":{\n" +
" \"INPUNT\": \"I\",\n" +
" \"MESSAGE_01\": \"RSTW\",\n" +
" \"MESSAGE_02\": \"MNXTYP\",\n" +
" \"MESSAGE_03\": \"RSTWERDCV\",\n" +
" \"SEND_TIME\": \"20-NOV-2011 04:53:04 p.m.\",\n" +
" \"RCV_ID\": \"ABGRCV\",\n" +
" \"FORMAT0_MONTO\": \"200,000,300.00\",\n" +
" \"FORMATO_MONEDA\": \"USD\",\n" +
" \"CONTROL_01\": \"MSG1RCVSND\",\n" +
" \"CONTROL_02\": \"MSG2RCVSND\",\n" +
" \"CONTROL_03\": \"MSG3RCVSND\"\n" +
" }\n" +
"}";
ObjectMapper objectMapper = new ObjectMapper();
LinkedHashMap hashMap = objectMapper.readValue(json, LinkedHashMap.class);
Event event = new Event(hashMap);
System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(event));
}
public static class Event {
#JsonProperty("event")
private LinkedHashMap event;
public Event(LinkedHashMap event){
this.event = event;
}
}
}
I have the following JSON
"music": [
{
"play_offset_ms":10780,
"artists":[
{
"name":"Adele"
}
],
"lyrics":{
"copyrights":[
"Sony/ATV Music Publishing LLC",
"Universal Music Publishing Group"
]
},
"acrid":"6049f11da7095e8bb8266871d4a70873",
"album":{
"name":"Hello"
},
"label":"XL Recordings",
"external_ids":{
"isrc":"GBBKS1500214",
"upc":"886445581959"
},
"result_from":3,
"contributors":{
"composers":[
"Adele Adkins",
"Greg Kurstin"
],
"lyricists":[
"ADELE ADKINS",
"GREGORY KURSTIN"
]
},
"title":"Hello",
"duration_ms":295000,
"score":100,
"external_metadata":{
"deezer":{
"track":{
"id":"110265034"
},
"artists":[
{
"id":"75798"
}
],
"album":{
"id":"11483764"
}
},
"spotify":{
"track":{
"id":"4aebBr4JAihzJQR0CiIZJv"
},
"artists":[
{
"id":"4dpARuHxo51G3z768sgnrY"
}
],
"album":{
"id":"7uwTHXmFa1Ebi5flqBosig"
}
},
"musicstory":{
"track":{
"id":"13106540"
},
"release":{
"id":"2105405"
},
"album":{
"id":"931271"
}
},
"youtube":{
"vid":"YQHsXMglC9A"
}
},
"release_date":"2015-10-23"
}
]
I want to fetch the value vid from the youtube object in external_metadata. I am getting other required values but couldn't get the youtube id with what I tried. Just attaching a code snippet of what I tried.
I tried the following code:
try {
JSONObject j = new JSONObject(result);
JSONObject j1 = j.getJSONObject("status");
int j2 = j1.getInt("code");
if(j2 == 0){
JSONObject metadata = j.getJSONObject("metadata");
//
if (metadata.has("music")) {
wave.setVisibility(View.GONE);
JSONArray musics = metadata.getJSONArray("music");
for(int i=0; i<musics.length(); i++) {
JSONObject tt = (JSONObject) musics.get(i);
String title = tt.getString("title");
JSONArray artistt = tt.getJSONArray("artists");
JSONObject art = (JSONObject) artistt.get(0);
String artist = art.getString("name");
JSONObject extMETA = tt.getJSONObject("external_metadata");
JSONObject youtube = extMETA.getJSONObject("youtube");
String ytID = youtube.getString("vid");}}
I did not get the expected output with what i tried , i know i am doing something wrong. Need your guidance.
I tried to run your code with sample JSON you have provided and It seems to work perfectly fine. I used google's gson library.
Below is the complete code.
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class Test {
static String jsonString = "{ \"music\": [{ \"play_offset_ms\": 10780, \"artists\": [{ \"name\": \"Adele\" }], \"lyrics\": { \"copyrights\": [ \"Sony/ATV Music Publishing LLC\", \"Universal Music Publishing Group\" ] }, \"acrid\": \"6049f11da7095e8bb8266871d4a70873\", \"album\": { \"name\": \"Hello\" }, \"label\": \"XL Recordings\", \"external_ids\": { \"isrc\": \"GBBKS1500214\", \"upc\": \"886445581959\" }, \"result_from\": 3, \"contributors\": { \"composers\": [ \"Adele Adkins\", \"Greg Kurstin\" ], \"lyricists\": [ \"ADELE ADKINS\", \"GREGORY KURSTIN\" ] }, \"title\": \"Hello\", \"duration_ms\": 295000, \"score\": 100, \"external_metadata\": { \"deezer\": { \"track\": { \"id\": \"110265034\" }, \"artists\": [{ \"id\": \"75798\" }], \"album\": { \"id\": \"11483764\" } }, \"spotify\": { \"track\": { \"id\": \"4aebBr4JAihzJQR0CiIZJv\" }, \"artists\": [{ \"id\": \"4dpARuHxo51G3z768sgnrY\" }], \"album\": { \"id\": \"7uwTHXmFa1Ebi5flqBosig\" } }, \"musicstory\": { \"track\": { \"id\": \"13106540\" }, \"release\": { \"id\": \"2105405\" }, \"album\": { \"id\": \"931271\" } }, \"youtube\": { \"vid\": \"YQHsXMglC9A\" } }, \"release_date\": \"2015-10-23\" }] }";
public static void main(String[] args) throws Exception {
System.out.println("START");
readJson(jsonString);
System.out.println("END");
}
public static void readJson(String jsonString) throws Exception {
JsonObject metadata = new JsonParser().parse(jsonString).getAsJsonObject();
JsonArray musics = metadata.get("music").getAsJsonArray();
for (int i = 0; i < musics.size(); i++) {
JsonObject tt = musics.get(i).getAsJsonObject();
String title = tt.get("title").getAsString();
JsonArray artistt = tt.get("artists").getAsJsonArray();
JsonObject art = artistt.get(0).getAsJsonObject();
String artist = art.get("name").getAsString();
JsonObject extMETA = tt.get("external_metadata").getAsJsonObject();
JsonObject youtube = extMETA.get("youtube").getAsJsonObject();
String ytID = youtube.get("vid").getAsString();
System.out.println("ytID => "+ ytID);
}
}
}
Output:
Verify that the metadata variable has its value.
JSONObject jsonObject = new JSONObject(json);
Log.e("json structure : ", jsonObject.toString());
Use the following code when importing Json File from "Assets".
InputStream inputStream = getAssets().open("item.json");
int size = inputStream.available();
byte[] buffer = new byte[size];
inputStream.read(buffer);
inputStream.close();
json = new String(buffer, StandardCharsets.UTF_8);
If you have a Gson library, you can also access it in the "Class" format.
Gson gson = new Gson();
ItemVO itemVO = gson.fromJson(json, new TypeToken<ItemVO>() {
}.getType());
if (!itemVO.name != null) {
Log.e("name : ", itemVO.name);
} else {
Log.e("name : ", "name is Null");
}
Actual problem is in your JSONObject creation from sample data. Check below:
String data = "{\"metadata\":{\"timestamp_utc\":\"2020-01-02 09:40:56\",\"music\":[{\"play_offset_ms\":10780,\"artists\":[{\"name\":\"Adele\"}],\"lyrics\":{\"copyrights\":[\"Sony/ATV Music Publishing LLC\",\"Universal Music Publishing Group\"]},\"acrid\":\"6049f11da7095e8bb8266871d4a70873\",\"album\":{\"name\":\"Hello\"},\"label\":\"XL Recordings\",\"external_ids\":{\"isrc\":\"GBBKS1500214\",\"upc\":\"886445581959\"},\"result_from\":3,\"contributors\":{\"composers\":[\"Adele Adkins\",\"Greg Kurstin\"],\"lyricists\":[\"ADELE ADKINS\",\"GREGORY KURSTIN\"]},\"title\":\"Hello\",\"duration_ms\":295000,\"score\":100,\"external_metadata\":{\"deezer\":{\"track\":{\"id\":\"110265034\"},\"artists\":[{\"id\":\"75798\"}],\"album\":{\"id\":\"11483764\"}},\"spotify\":{\"track\":{\"id\":\"4aebBr4JAihzJQR0CiIZJv\"},\"artists\":[{\"id\":\"4dpARuHxo51G3z768sgnrY\"}],\"album\":{\"id\":\"7uwTHXmFa1Ebi5flqBosig\"}},\"musicstory\":{\"track\":{\"id\":\"13106540\"},\"release\":{\"id\":\"2105405\"},\"album\":{\"id\":\"931271\"}},\"youtube\":{\"vid\":\"YQHsXMglC9A\"}},\"release_date\":\"2015-10-23\"}]},\"cost_time\":0.2110002040863,\"status\":{\"msg\":\"Success\",\"version\":\"1.0\",\"code\":0},\"result_type\":0}";
try {
JSONObject jsonObject = new JSONObject(data);
JSONObject metadata = jsonObject.getJSONObject("metadata");
JSONArray musics = metadata.getJSONArray("music");
for (int i = 0; i < musics.length(); i++) {
JSONObject tt = (JSONObject) musics.get(i);
String title = tt.getString("title");
JSONArray artistt = tt.getJSONArray("artists");
JSONObject art = (JSONObject) artistt.get(0);
String artist = art.getString("name");
JSONObject extMETA = tt.getJSONObject("external_metadata");
JSONObject youtube = extMETA.getJSONObject("youtube");
String ytID = youtube.getString("vid");
Log.v("VID", ytID);
}
} catch (Exception ex) {
ex.printStackTrace();
}
Given the following Json data:
"values": [
{
"type": "any",
"value": "MO918038B",
"key": "nino"
},
{
"type": "any",
"value": "1956-11-18",
"key": "dob"
},
{
"type": "any",
"value": "q",
"key": "memorableWord"
},
{
"type": "any",
"value": "E13468",
"key": "pin"
},
]
And the following Java class:
public void doStuff() {
try (Reader reader = new FileReader("global-vars.json")) {
JsonObject json = new Gson().fromJson(reader, JsonObject.class);
String reg = json.get("values").toString();
System.out.println(reg);
} catch (IOException e) {
e.printStackTrace();
}
}
I'm not clear, after searching, how best to obtain the "value" of, for example, "nino" which is = "MO918038B"
Type listType = new TypeToken<List<YourObjectClass>>() {}.getType();
List<YourObjectClass> yourList = new Gson().fromJson(yourJson, listType);
Since your posted JSON isn't RFC 4627 conformant, I assume this array is inside of an object.
Code would look like this:
public class YourClass {
class Value {
public String type;
public String value;
public String key;
}
public Value[] values;
}
public class App{
public static void main(String[] args) {
String json = "{ \"values\": [\n" +
"{\n" +
" \"type\": \"any\",\n" +
" \"value\": \"MO918038B\",\n" +
" \"key\": \"nino\"\n" +
"},\n" +
"{\n" +
" \"type\": \"any\",\n" +
" \"value\": \"1956-11-18\",\n" +
" \"key\": \"dob\"\n" +
"},\n" +
"{\n" +
" \"type\": \"any\",\n" +
" \"value\": \"q\",\n" +
" \"key\": \"memorableWord\"\n" +
"},\n" +
"{\n" +
" \"type\": \"any\",\n" +
" \"value\": \"E13468\",\n" +
" \"key\": \"pin\"\n" +
"}\n" +
"]}";
YourClass yourClass = new Gson().fromJson(json, YourClass.class);
for (YourClass.Value value : yourClass.values) {
if (value.key.equals("nino")) {
System.out.println(value.value);
}
}
}
}
I have following json data:-
{
"store": {
"book": [
{
"category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{
"category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
},
{
"category": "fiction",
"author": "Herman Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
},
{
"category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}
],
"bicycle": {
"color": "red",
"price": 19.95
}
},
"expensive": 10
}
Method to assert json:-
public void assertJsonvalue (String description, String jsonString,
String path, Object expectedValue) {
ObjectMapper objectMapper = new ObjectMapper();
Map<String, Object> jsonMap = null;
try {
jsonMap = objectMapper.readValue(jsonString,
new TypeReference<Map<String, Object>>() {
});
} catch (IOException e) {
fail("Could not parse json from string:" + jsonString);
}
Object actualValue = null;
try {
actualValue = PropertyUtils.getProperty(jsonMap, path);
System.out.println("actualValue" + actualValue);
} catch (IllegalAccessException e) {
// error here
}
assertEquals(description, expectedValue, actualValue);
}
When I try to get json value from by using the following, Its works well.
assertJsonValue("bicycle color", json, "store.bicycle.color", "red");
I want to get array value from json such as details of 1st book.
I have tried the following, that doesn't help me out.
json paths are as follows:-
"store.book[0]"
"store.book.[0]"
"store.book.category"
How Can I do this ?
According to this answer, you should be able to get the mentioned properties like this:
assertJsonValue("...", json, "store.(book)[0].category", "reference");
Edit:
Which version of jackson and beanutils are you using? I've modified your method a bit and made a simple test case, using beanutils 1.9.2 and jackson 2.6.5 tests seem to pass:
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.beanutils.PropertyUtils;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.*;
public class TestJson {
private static final String JSON = "{\n" +
" \"store\": {\n" +
" \"book\": [\n" +
" {\n" +
" \"category\": \"reference\",\n" +
" \"author\": \"Nigel Rees\",\n" +
" \"title\": \"Sayings of the Century\",\n" +
" \"price\": 8.95\n" +
" }\n" +
" ],\n" +
" \"bicycle\": {\n" +
" \"color\": \"red\",\n" +
" \"price\": 19.95\n" +
" }\n" +
" },\n" +
" \"expensive\": 10\n" +
"}";
#Test
public void testJson() {
assertTrue(assertJsonValue(JSON, "store.(book)[0].category", "reference"));
assertTrue(assertJsonValue(JSON, "store.(book)[0].author", "Nigel Rees"));
assertTrue(assertJsonValue(JSON, "store.(book)[0].title", "Sayings of the Century"));
assertTrue(assertJsonValue(JSON, "store.(book)[0].price", 8.95));
}
public boolean assertJsonValue(String jsonString,
String path,
Object expectedValue) {
ObjectMapper objectMapper = new ObjectMapper();
try {
Object actual = PropertyUtils
.getProperty(objectMapper.readValue(jsonString, Object.class), path);
if (actual.equals(expectedValue)) {
return true;
}
} catch (IOException | ReflectiveOperationException e) {
// handle error
}
return false;
}
}
I am new to JSON programming in J2ME.
I discovered that Json is used to exchange data much like XML.
I want to know about the exchange in Array object from JSONtoObject and vice versa
Below written is code where I convert from JSON to Object and vice versa.
But I don't know about how to do for complex data structure like arrays etc.
// App Loader
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
public class AppLoader extends MIDlet {
public AppLoader() {
// TODO Auto-generated constructor stub
// Converting Object to JSON
UserData data=new UserData();
data.setId(10);
data.setName("Yatin");
data.setDescription("Testing JSON in J2ME");
System.out.println("Convert to JSON"+data.toJSON());
//Convert JSON to Object
String sample="{\"id\":99,\"name\":\"Tester\",\"description\":\"This is JSON Data\"}";
UserData data2=new UserData();
data2.fromJSON(sample);
System.out.println("Convert from JSON "+data2);
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
// TODO Auto-generated method stub
}
protected void pauseApp() {
// TODO Auto-generated method stub
}
protected void startApp() throws MIDletStateChangeException {
// TODO Auto-generated method stub
}
}
In this class I created getters and setters for the String type of objects and then created JsonObject to create a JSON object to create a JSON object and then vice versa as per functions toJSON() and fromJSON()
// User Data class
import org.json.me.JSONException;
import org.json.me.JSONObject;
public class UserData {
private int id;
private String name;
private String description;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String toString()
{
return getId()+"-"+getName()+"-"+getDescription();
}
public String toJSON() {
// TODO Auto-generated method stub
JSONObject inner=new JSONObject();
try {
inner.put("id",getId());
inner.put("description", getDescription());
inner.put("name", getName());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return inner.toString();
}
public void fromJSON(String jsonString) {
// TODO Auto-generated method stub
try {
JSONObject json=new JSONObject(jsonString);
setId(json.getInt("id"));
setDescription(json.getString("description"));
setName(json.getString("name"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
i found a better link for this question
http://jimmod.com/blog/2011/09/java-me-j2me-json-implementation-for-array-object/
Check this link for different JSON Data Set Sample
One Example for your Understanding::: JSON String Nested with Arrays
{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters":
{
"batter":
[
{ "id": "1001", "type": "Regular" },
{ "id": "1002", "type": "Chocolate" },
{ "id": "1003", "type": "Blueberry" },
{ "id": "1004", "type": "Devil's Food" }
]
},
"topping":
[
{ "id": "5001", "type": "None" },
{ "id": "5002", "type": "Glazed" },
{ "id": "5005", "type": "Sugar" },
{ "id": "5007", "type": "Powdered Sugar" },
{ "id": "5006", "type": "Chocolate with Sprinkles" },
{ "id": "5003", "type": "Chocolate" },
{ "id": "5004", "type": "Maple" }
]
}
To check its valid or not check this link (JSON Validator)
To check JSON Viewer
So Here is code take look::
String json = "{\"id\":\"0001\",\"type\":\"donut\",\"name\":\"Cake\""
+ ",\"ppu\":0.55,\"batters\":{\"batter\":["
+ "{\"id\":\"1001\",\"type\":\"Regular\"},{\"id\":\"1002\","
+ "\"type\":\"Chocolate\"},{\"id\":\"1003\","
+ "\"type\": \"Blueberry\" },{ \"id\": \"1004\", "
+ "\"type\": \"Devil's Food\" } ] },"
+ " \"topping\":["
+ "{ \"id\": \"5001\", \"type\": \"None\" },"
+ "{ \"id\": \"5002\", \"type\": \"Glazed\" },"
+ "{ \"id\": \"5005\", \"type\": \"Sugar\" },"
+ "{ \"id\": \"5007\", \"type\": \"Powdered Sugar\" },"
+ " { \"id\": \"5006\", \"type\": \"Chocolate with Sprinkles\" },"
+ "{ \"id\": \"5003\", \"type\": \"Chocolate\" },"
+ "{ \"id\": \"5004\", \"type\": \"Maple\" }]}";
try {
JSONObject root = new JSONObject(json);
String id = root.getString("id");
double dd = root.getDouble("ppu");
System.out.println(""+id);
System.out.println(""+dd);
JSONObject batters=new JSONObject(root.getString("batters"));
JSONArray batter=new JSONArray(batters.getString("batter"));
for(int j=0;j<batter.length();j++){
JSONObject navgt_batter=new JSONObject(batter.getString(j));
String id_batter= navgt_batter.getString("id");
String type_batter=navgt_batter.getString("type");
System.out.println(""+id+" "+type_batter);
}
JSONArray topping=root.getJSONArray("topping");
for(int k=0;k<topping.length();k++){
JSONObject navgt_batter=new JSONObject(topping.getString(k));
String id_top =navgt_batter.getString("id");
String type_top=navgt_batter.getString("type");
System.out.println(""+id_top+" "+type_top);
}
} catch (JSONException ex) {
ex.printStackTrace();
}
You can use your same concept to set & get data like above you did. complex data structure always easy to handle in JSON, don't worry about it. Thanks
In the below link
http://jimmod.com/blog/2011/09/java-me-j2me-json-implementation-for-array-object/
they have explained how a JSONArray is used
public void fromJSON(String jsonString) {
try {
JSONObject json = new JSONObject(jsonString);
setApi_status(json.getString("api_status"));
JSONArray jsonArray = json.getJSONArray("threads");
int total = jsonArray.length();
ThreadData[] threads = new ThreadData[total];
for (int i=0;i<total;i++) {
String threadsJSON = jsonArray.getString(i);
threads[i] = new ThreadData();
threads[i].fromJSON(threadsJSON);
}
setThreads(threads);
} catch (JSONException ex) {
ex.printStackTrace();
}
}
public String toJSON() {
JSONObject inner = new JSONObject();
try {
inner.put("api_status", getApi_status());
JSONArray jsonArray = new JSONArray();
ThreadData[] threads = getThreads();
for (int i=0;i<threads.length;i++) {
jsonArray.put(threads[i].toJSON());
}
inner.put("threads", jsonArray);
} catch (JSONException ex) {
ex.printStackTrace();
}
return inner.toString();
}
Where Threaddata is a class defined for a JSONObject and it has been made in array object
check out the link
It pretty the same way .. all you need is to just loop through the array ... i added tags to your sample JSON data
String sample = "{\"id\":99,\"name\":\"Tester\",\"description\":\"This is JSON Data\",\"tags\":[\"eat\",\"swim\",\"sleep\"]}";
try {
JSONObject objSample = new JSONObject(sample);
JSONArray array = new JSONArray(objSample.getJSONArray("tags").toString());
System.out.println(objSample.get("id").toString());
System.out.println(objSample.get("name").toString());
System.out.println(objSample.get("description").toString());
for (int i = 0; i < array.length(); i++) {
System.out.println(array.get(i).toString());
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
Output
99
Tester
This is JSON Data
eat
swim
sleep
I hope this helps
Thanks
:)