I am working on a Java api - using Spring Boot - I would like to create a controller that exports data from the db - into a csv that a user can download.
This is an example of what I have making Json responses.
// get chart
#SuppressWarnings("unchecked")
public Object getChart() {
// build clean object
JSONObject contents = new JSONObject();
//inverse bubble chart
JSONObject chart = new JSONObject();
chart.put("label", "250 applicants");
chart.put("value", 120);
contents.put("chart", chart);
contents.put("number", "0202 000 000");
JSONObject json = new JSONObject();
json.put("contents", contents);
return json;
}
I've seen this example -- but its being called from a reactjs framework - so not sure how I would fetch the HttpServletResponse?
Create and Download CSV file Java(Servlet)
would I invoke the api as usual?
//api/getMyCsv
#SuppressWarnings("unchecked")
#RequestMapping(value = {"/api/getMyC"}, method = RequestMethod.GET)
#CrossOrigin(origins = {"*"})
public ResponseEntity<?> getHome(
//HttpServletRequest request
) throws Exception {
JSONObject chart = getChart();
JSONArray data = new JSONArray();
data.add(chart);
//create empty response
JSONObject response = new JSONObject();
//create success response
response.put("data", data);
response.put("status", "success");
response.put("msg", "fetched csv");
return new ResponseEntity<>(response, HttpStatus.OK);
}
so with the react - using axios
export function fetchCsv(data) {
let url = "http://www.example.com/api/getMyC";
return function (dispatch) {
axios.get(url, {
params: data
})
.then(function (response) {
response = response.data.data;
dispatch(alertSuccess(response));
})
.catch(function (error) {
dispatch(alertFail(error));
});
}
}
CSV is just comma separated values right?
So, you can represent a row of data for example, as a class.
Take an address:
30 my street, my town, my country
if I wanted to represent that data as a class, and later as CSV data I'd make a class something like this:
public class AddressCSV{
private String street;
private String town;
private String country;
public AddressCSV(String street, String town, String country){
this.street = street;
this.town = town;
this.country = country;
}
// getters and setters here
// here you could have a method called generateCSV() for example
// or you could override the toString() method like this
#Override
public String toString(){
return street + "," + town + "," + country + "\n"; // Add the '\n' if you need a new line
}
}
Then you use it the same way as your JSONObject, except instead of returning the whole object you do return address.toString();
This is a very simple example of course. Checkout the StringBuilder class if your have a lot of things to build.
Overriding the toString() method means you can do things like pass your object like System.out.printline(address) and it will print the CSV.
The Spring way to help (un)marshaling data is to implement and register an HttpMessageConverter.
You could implement one that specifically handles MediaType text/csv, and supports whatever object types you decide to implement, e.g.
List<List<?>> - Row is a list of values, auto-converted to string.
List<Object[]> - Row is an array of values, auto-converted to string.
List<String[]> - Row is an array of string values.
List<?> - Row is an bean object, field names added as header row.
You may even implement your own field annotations to control column order and header row values.
You could also make it understand JAXB and/or JSON annotations.
With such a converter in place, it's now easy to write Controller methods returning CSV:
#GetMapping(path="/api/getMyC", produces="text/csv")
public List<String[]> getMyCAsCsv() {
List<Object[]> csv = Arrays.asList(
new Object[] { "First Name", "Last Name", "Age" },
new Object[] { "John" , "Doe" , 33 },
new Object[] { "Jane" , "Smith" , 29 }
);
return csv;
}
DO NOT try doing basic String trickery because the address, especially the street is bound to contain characters such as commas, quotes or line endings. This can easily mess up the CSV output. These characters need to be properly escaped in order to generate a parseable CSV output. Use a CSV library for that instead.
Example with univocity-parsers:
ResultSet rs = queryDataFromYourDb();
StringWriter output = new StringWriter(); //writing to a String to make things easy
CsvRoutines csvRoutine = new CsvRoutines();
csvRoutine.write(rs, output);
System.out.println(output.toString());
For performance, can write to an OutputStream directly and add more stuff to it after dumping your ResultSet into CSV. In such case you will want to keep the output open for writing. In this case call:
csvRoutine.setKeepResourcesOpen(true);
Before writing the ResultSet. You'll have to close the resultSet after writing.
Disclaimer: I'm the author of this library. It's open-source and free.
Related
I've a problem trying to make my page printing out the JSONObject in the order i want. In my code, I entered this:
JSONObject myObject = new JSONObject();
myObject.put("userid", "User 1");
myObject.put("amount", "24.23");
myObject.put("success", "NO");
However, when I see the display on my page, it gives:
JSON formatted string: [{"success":"NO", "userid":"User 1", "bid":24.23}]
I need it in the order of userid, amount, then success. Already tried re-ordering in the code, but to no avail. I've also tried .append....need some help here thanks!!
You cannot and should not rely on the ordering of elements within a JSON object.
From the JSON specification at https://www.json.org/
An object is an unordered set of
name/value pairs
As a consequence,
JSON libraries are free to rearrange the order of the elements as they see fit.
This is not a bug.
I agree with the other answers. You cannot rely on the ordering of JSON elements.
However if we need to have an ordered JSON, one solution might be to prepare a LinkedHashMap object with elements and convert it to JSONObject.
#Test
def void testOrdered() {
Map obj = new LinkedHashMap()
obj.put("a", "foo1")
obj.put("b", new Integer(100))
obj.put("c", new Double(1000.21))
obj.put("d", new Boolean(true))
obj.put("e", "foo2")
obj.put("f", "foo3")
obj.put("g", "foo4")
obj.put("h", "foo5")
obj.put("x", null)
JSONObject json = (JSONObject) obj
logger.info("Ordered Json : %s", json.toString())
String expectedJsonString = """{"a":"foo1","b":100,"c":1000.21,"d":true,"e":"foo2","f":"foo3","g":"foo4","h":"foo5"}"""
assertEquals(expectedJsonString, json.toString())
JSONAssert.assertEquals(JSONSerializer.toJSON(expectedJsonString), json)
}
Normally the order is not preserved as below.
#Test
def void testUnordered() {
Map obj = new HashMap()
obj.put("a", "foo1")
obj.put("b", new Integer(100))
obj.put("c", new Double(1000.21))
obj.put("d", new Boolean(true))
obj.put("e", "foo2")
obj.put("f", "foo3")
obj.put("g", "foo4")
obj.put("h", "foo5")
obj.put("x", null)
JSONObject json = (JSONObject) obj
logger.info("Unordered Json : %s", json.toString(3, 3))
String unexpectedJsonString = """{"a":"foo1","b":100,"c":1000.21,"d":true,"e":"foo2","f":"foo3","g":"foo4","h":"foo5"}"""
// string representation of json objects are different
assertFalse(unexpectedJsonString.equals(json.toString()))
// json objects are equal
JSONAssert.assertEquals(JSONSerializer.toJSON(unexpectedJsonString), json)
}
You may check my post too: http://www.flyingtomoon.com/2011/04/preserving-order-in-json.html
u can retain the order, if u use JsonObject that belongs to com.google.gson :D
JsonObject responseObj = new JsonObject();
responseObj.addProperty("userid", "User 1");
responseObj.addProperty("amount", "24.23");
responseObj.addProperty("success", "NO");
Usage of this JsonObject doesn't even bother using Map<>
CHEERS!!!
Real answer can be found in specification, json is unordered.
However as a human reader I ordered my elements in order of importance. Not only is it a more logic way, it happened to be easier to read. Maybe the author of the specification never had to read JSON, I do.. So, Here comes a fix:
/**
* I got really tired of JSON rearranging added properties.
* Specification states:
* "An object is an unordered set of name/value pairs"
* StackOverflow states:
* As a consequence, JSON libraries are free to rearrange the order of the elements as they see fit.
* I state:
* My implementation will freely arrange added properties, IN SEQUENCE ORDER!
* Why did I do it? Cause of readability of created JSON document!
*/
private static class OrderedJSONObjectFactory {
private static Logger log = Logger.getLogger(OrderedJSONObjectFactory.class.getName());
private static boolean setupDone = false;
private static Field JSONObjectMapField = null;
private static void setupFieldAccessor() {
if( !setupDone ) {
setupDone = true;
try {
JSONObjectMapField = JSONObject.class.getDeclaredField("map");
JSONObjectMapField.setAccessible(true);
} catch (NoSuchFieldException ignored) {
log.warning("JSONObject implementation has changed, returning unmodified instance");
}
}
}
private static JSONObject create() {
setupFieldAccessor();
JSONObject result = new JSONObject();
try {
if (JSONObjectMapField != null) {
JSONObjectMapField.set(result, new LinkedHashMap<>());
}
}catch (IllegalAccessException ignored) {}
return result;
}
}
from lemiorhan example
i can solve with just change some line of lemiorhan's code
use:
JSONObject json = new JSONObject(obj);
instead of this:
JSONObject json = (JSONObject) obj
so in my test code is :
Map item_sub2 = new LinkedHashMap();
item_sub2.put("name", "flare");
item_sub2.put("val1", "val1");
item_sub2.put("val2", "val2");
item_sub2.put("size",102);
JSONArray itemarray2 = new JSONArray();
itemarray2.add(item_sub2);
itemarray2.add(item_sub2);//just for test
itemarray2.add(item_sub2);//just for test
Map item_sub1 = new LinkedHashMap();
item_sub1.put("name", "flare");
item_sub1.put("val1", "val1");
item_sub1.put("val2", "val2");
item_sub1.put("children",itemarray2);
JSONArray itemarray = new JSONArray();
itemarray.add(item_sub1);
itemarray.add(item_sub1);//just for test
itemarray.add(item_sub1);//just for test
Map item_root = new LinkedHashMap();
item_root.put("name", "flare");
item_root.put("children",itemarray);
JSONObject json = new JSONObject(item_root);
System.out.println(json.toJSONString());
JavaScript objects, and JSON, have no way to set the order for the keys. You might get it right in Java (I don't know how Java objects work, really) but if it's going to a web client or another consumer of the JSON, there is no guarantee as to the order of keys.
Download "json simple 1.1 jar" from this https://code.google.com/p/json-simple/downloads/detail?name=json_simple-1.1.jar&can=2&q=
And add the jar file to your lib folder
using JSONValue you can convert LinkedHashMap to json string
For those who're using maven, please try com.github.tsohr/json
<!-- https://mvnrepository.com/artifact/com.github.tsohr/json -->
<dependency>
<groupId>com.github.tsohr</groupId>
<artifactId>json</artifactId>
<version>0.0.1</version>
</dependency>
It's forked from JSON-java but switch its map implementation with LinkedHashMap which #lemiorhan noted above.
As all are telling you, JSON does not maintain "sequence" but array does, maybe this could convince you:
Ordered JSONObject
For Java code, Create a POJO class for your object instead of a JSONObject.
and use JSONEncapsulator for your POJO class.
that way order of elements depends on the order of getter setters in your POJO class.
for eg. POJO class will be like
Class myObj{
String userID;
String amount;
String success;
// getter setters in any order that you want
and where you need to send your json object in response
JSONContentEncapsulator<myObj> JSONObject = new JSONEncapsulator<myObj>("myObject");
JSONObject.setObject(myObj);
return Response.status(Status.OK).entity(JSONObject).build();
The response of this line will be
{myObject : {//attributes order same as getter setter order.}}
The main intention here is to send an ordered JSON object as response. We don't need javax.json.JsonObject to achieve that. We could create the ordered json as a string.
First create a LinkedHashMap with all key value pairs in required order. Then generate the json in string as shown below.
Its much easier with Java 8.
public Response getJSONResponse() {
Map<String, String> linkedHashMap = new LinkedHashMap<>();
linkedHashMap.put("A", "1");
linkedHashMap.put("B", "2");
linkedHashMap.put("C", "3");
String jsonStr = linkedHashMap.entrySet().stream()
.map(x -> "\"" + x.getKey() + "\":\"" + x.getValue() + "\"")
.collect(Collectors.joining(",", "{", "}"));
return Response.ok(jsonStr).build();
}
The response return by this function would be following:
{"A":"1","B":"2","C":"3"}
Underscore-java uses linkedhashmap to store key/value for json. I am the maintainer of the project.
Map<String, Object> myObject = new LinkedHashMap<>();
myObject.put("userid", "User 1");
myObject.put("amount", "24.23");
myObject.put("success", "NO");
System.out.println(U.toJson(myObject));
I found a "neat" reflection tweak on "the interwebs" that I like to share.
(origin: https://towardsdatascience.com/create-an-ordered-jsonobject-in-java-fb9629247d76)
It is about to change underlying collection in org.json.JSONObject to an un-ordering one (LinkedHashMap) by reflection API.
I tested succesfully:
import java.lang.reflect.Field;
import java.util.LinkedHashMap;
import org.json.JSONObject;
private static void makeJSONObjLinear(JSONObject jsonObject) {
try {
Field changeMap = jsonObject.getClass().getDeclaredField("map");
changeMap.setAccessible(true);
changeMap.set(jsonObject, new LinkedHashMap<>());
changeMap.setAccessible(false);
} catch (IllegalAccessException | NoSuchFieldException e) {
e.printStackTrace();
}
}
[...]
JSONObject requestBody = new JSONObject();
makeJSONObjLinear(requestBody);
requestBody.put("username", login);
requestBody.put("password", password);
[...]
// returned '{"username": "billy_778", "password": "********"}' == unordered
// instead of '{"password": "********", "username": "billy_778"}' == ordered (by key)
Just add the order with this tag
#JsonPropertyOrder({ "property1", "property2"})
Not sure if I am late to the party but I found this nice example that overrides the JSONObject constructor and makes sure that the JSON data are output in the same way as they are added. Behind the scenes JSONObject uses the MAP and MAP does not guarantee the order hence we need to override it to make sure we are receiving our JSON as per our order.
If you add this to your JSONObject then the resulting JSON would be in the same order as you have created it.
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.LinkedHashMap;
import org.json.JSONObject;
import lombok.extern.java.Log;
#Log
public class JSONOrder {
public static void main(String[] args) throws IOException {
JSONObject jsontest = new JSONObject();
try {
Field changeMap = jsonEvent.getClass().getDeclaredField("map");
changeMap.setAccessible(true);
changeMap.set(jsonEvent, new LinkedHashMap<>());
changeMap.setAccessible(false);
} catch (IllegalAccessException | NoSuchFieldException e) {
log.info(e.getMessage());
}
jsontest.put("one", "I should be first");
jsonEvent.put("two", "I should be second");
jsonEvent.put("third", "I should be third");
System.out.println(jsonEvent);
}
}
Just use LinkedHashMap to keep de order and transform it to json with jackson
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.LinkedHashMap;
LinkedHashMap<String, Object> obj = new LinkedHashMap<String, Object>();
stats.put("aaa", "aaa");
stats.put("bbb", "bbb");
stats.put("ccc", "ccc");
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
System.out.println(json);
maven dependency
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.10.7</version>
</dependency>
I just want the order for android unit tests that are somehow randomly changing overtime with this cool org.json.JSONObject, even thou it looks like it uses linked map but probably depends on api you compile it with or something, so it has different impl. with different android api probably.
I would suggest something like this:
object Json {
#SuppressLint("DiscouragedPrivateApi")
fun Object() = org.json.JSONObject().apply {
runCatching {
val nameValuePairs: Field = javaClass.getDeclaredField("nameValuePairs")
nameValuePairs.isAccessible = true
nameValuePairs.set(this, LinkedHashMap<String, Any?>())
}.onFailure { it.printStackTrace() }
}
}
Usage:
val jsonObject = Json.Object()
...
This is just some possibility I use it little differently so I modified it to post here. Sure gson or other lib is another option.
Suggestions that specification is bla bla are so shortsighted here, why you guys even post it, who cares about 15 years old json spec, everyone wants it ordered anyway.
My database tables has a few jsonb columns. I am using PostgreSQL e.g.
CREATE TABLE trades (
id serial NOT NULL,
accounts jsonb,
//..
//..
);
I need to map these jsonb columns to my data model using Spring RowMapper mapRow():
public class DataModelRowMapper implements RowMapper<TestModel> {
#Override
public TestModel mapRow(final ResultSet rs,
final int rowNum) throws SQLException {
List<Account> accounts = jsonParser.parse(rs.getString("accounts"), new TypeReference<List<Account>>() {
});
//other jsonb columns
Account account = accounts.stream()
.filter(account -> account.getType() == Type.CLIENT)
.findFirst()
.orElse(new Account());
final TestModel testModel = new TestModel();
testModel.setId(rs.getString("id"));
testModel.setAccountName(account.getName());
return testModel;
}
}
Inside mapRow(), I parse the json to a Java List and then stream through to find the appropriate value as multiple accounts are returned. I have a few additional jsonb columns for which I do similar operations inside mapRow().
Previously, I was returning the exact values from the SQL query itself which proved to be slow and then moved this filtering logic to inside mapRow() in java code as the intention is to increase performance and return the result.
My question is, should I be parsing and filtering logic inside mapRow ? Is there a better faster way of loading jsonb data and mapping to TestModel accountName string property ?
My issue is, the sql query runs quick <1 ms on the db, but the java layer is adding some overhead.
If you look at the whole system, you may not need to parse into the fields at all.
for example, in most cases, it is required to return the JSON without modifications. just return the string. no need to parse back and forth, it's really faster.
example spring mvc:
// a method that returns a list of objects in JSON by search criteria
#RequestMapping(value = "/getAll", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody
void getAll(HttpServletResponse response, #RequestBody final Entity request) throws IOException {
List<String> res = null;
try {
List<Entity> regList = entityDAO.getAll(request); // get from DB list of objects with JSON
res = regList.stream().map(h -> h.getJson_obj()).collect(Collectors.toList()); // just collect JSONs
// res = regList.stream().map(h -> h.getJson_obj().replaceFirst("\\{", "{ \"vehicle_num\":" + h.getVehicle_num() + ",")).collect(Collectors.toList()); //it is also possible to add dynamic data without parsing
} catch (Exception e) {
logger.error("getAll ", e);
}
String resStr = "[" + res.stream().filter(t -> t != null).collect(Collectors.joining(", ")) + "]"; // join in one String
response.setHeader("Content-Type", "application/json;charset=UTF-8");
response.setStatus(200);
response.getWriter().println(resStr);
}
ps sorry, I can't leave a comment, so the answer.
I have a Java POJO
public class TagBean {
private String type;
private String id;
public TagBean(String type, String id) {
this.type = type;
this.id = id;
}
// getters
// setters
}
I'm building pojo's and adding them to a List, as
....
List<TagBean> channelsList = new ArrayList<>();
List<TagBean> showsList = new ArrayList<>();
for each <business logic> {
if value=channels {
channelsList.add(new TagBean(...));
}
if value=shows {
showsList.add(new TagBean(...));
}
}
Gson gson = new GsonBuilder().create();
JsonObject tjsonObject = new JsonObject();
tjsonObject.addProperty("channels", gson.toJson(channelsList));
tjsonObject.addProperty("shows", gson.toJson(showsList));
JsonObject mainjsonObject = mainjsonObject.add("tags", tjsonObject);
return mainjsonObject;
My output is:
{
"tags": {
"channels": "[{\"type\":\"channel\",\"id\":\"channel\",\"name\":\"Channel\",\"parent\":\"SXM\"}]",
"shows": "[{\"type\":\"shows\",\"id\":\"shows\",\"name\":\"Shows\",\"parent\":\"SXM\"},{\"type\":\"shows\",\"id\":\"howard\",\"name\":\"Howard Stern\",\"parent\":\"shows\"},{\"type\":\"shows\",\"id\":\"howardstern\",\"name\":\"Howard Stern\",\"parent\":\"howard\"}]",
"sports": "[]"
}
}
How can i remove the backslashes? So the output is like:
{
"tags": {
"channels": " [{"type":"channel","id":"channel","name":"Channel","parent":"SXM"}]",
"shows": "[{"type":"shows","id":"shows","name":"Shows","parent":"SXM"},{"type":"shows","id":"howard","name":"Howard Stern","parent":"shows"}....
There were few other posts, but none explained this.
The problem is caused by this:
tjsonObject.addProperty("channels", gson.toJson(channelsList));
What that is doing is converting channelsList to a string containing a representation of the list in JSON, then setting the property to that string. Since the string contains JSON meta-characters, they must be escaped when the strings are serialized ... a second time.
I think that you need to do this instead:
tjsonObject.add("channels", gson.toJsonTree(channelsList));
That should produce this:
{
"tags": {
"channels":
[{"type":"channel","id":"channel","name":"Channel","parent":"SXM"}],
"shows":
[{"type":"shows","id":"shows","name":"Shows","parent":"SXM"},
{"type":"shows","id":"howard","name":"Howard Stern","parent":"shows"}
....
That is slightly different to what your question asked for, but it has the advantage of being syntactically valid JSON!
String mainJsonStr = mainjsonObject.toString();
mainJsonStr = mainJsonStr.replace("\\\\", ""); //replace the \
System.out.println(mainJsonStr);
The problem is that gson.toJson returns a String, and
tjsonObject.addProperty("channels", gson.toJson(channelsList));
this will add channels as a string and not as a JSON object.
One possible solution is to convert the string returned from gson.toJson to JSON object first then add it to the parent JSON object like
Gson gson = new GsonBuilder().create();
JsonObject tjsonObject = new JsonObject();
tjsonObject.put("channels", new JsonObject(gson.toJson(channelsList)));
tjsonObject.put("shows", new JsonObject(gson.toJson(showsList)));
this will treat channels and shows as JSON object
All strings in java have to escape quotes in them. So jsonInString should have slashes in it. When you output jsonInString though it shouldn't have the quotes. Are you looking at it in a debugger or something?
Just parse json directly and check - will get the output
above solution is not working anymore since GSON 2.8.*
use gson.toJsonTree(jsonText).getAsString(); instead
This question already has answers here:
JSON parsing using Gson for Java
(11 answers)
How do I parse JSON in Android? [duplicate]
(3 answers)
How to parse JSON in Java
(36 answers)
Sending and Parsing JSON Objects in Android [closed]
(11 answers)
How to Parse a JSON Object In Android
(4 answers)
Closed 2 years ago.
I have a rather specific question about JSON parsing in Android.
I have a requirement to download a single JSON array containing information in the format shown below, the number of JSON objects in the array is variable. I need to retrieve all the JSON values in the array so each JSON value has to be stored as an android list named after the common JSON keys because there are many instances of each, e.g. a list for placenames keys [place1,place2,place3 = placename list], a list for questions key, etc. A caveat to this is I cannot use an android array to store these JSON key values since each time my app runs this download task I don't know how many JSON objects will be in the single array. Users can submit as much as they want at any time to the database.
[
{
"placename": "place1",
"latitude": "50",
"longitude": "-0.5",
"question": "place1 existed when?",
"answer1": "1800",
"answer2": "1900",
"answer3": "1950",
"answer4": "2000",
"correctanswer": "1900"
},
{
"placename": "place2",
"latitude": "51",
"longitude": "-0.5",
"question": "place2 existed when?",
"answer1": "800",
"answer2": "1000",
"answer3": "1200",
"answer4": "1400",
"correctanswer": "800"
},
{
"placename": "place3",
"latitude": "52",
"longitude": "-1",
"question": "place 3 was established when?",
"answer1": "2001",
"answer2": "2005",
"answer3": "2007",
"answer4": "2009",
"correctanswer": "2009"
}
]
Below is my code for mainactivity which I managed to get working but had a derp moment and realised I'd simply gone through and parsed out the values for each JSON key in each object as a single string value for each JSON key. Since the loop iterates it merely overwrites at each stage - the placename string is "place1", then "place2", then "place3" by the end of the loop, rather than ["place1","place2", "place3"] which is what I want. My question now is how would I go about parsing the JSONArray to extract all instances of each JSON value and output as a string list for each JSON key, the length of the list is determined by the number of Objects?
I've already got the template for a string list that stores all the JSON key values (commented out in the below code) but I'm not sure how to fill that String list from the JSON parsing process.
I've had a good look around and couldn't find anything specifically about JSON Array to Android List so help would be greatly appreciated. I'd also like to know if there is a way of maintaining association between each list (e.g. questions & answers for specific placenames) if I bundle the data out to different activities (e.g. q&a to a quiz and placenames/lat/lon to GPS). Can I do this by referencing the same index in the list? Or would I need to store these lists in local storage? an SQL lite database?
Thanks for your time and sorry for the overwhelmingly long post!
public class MainActivity extends Activity {
// The JSON REST Service I will pull from
static String dlquiz = "http://www.example.php";
// Will hold the values I pull from the JSON
//static List<String> placename = new ArrayList<String>();
static String placename = "";
static String latitude = "";
static String longitude = "";
static String question = "";
static String answer1 = "";
static String answer2 = "";
static String answer3 = "";
static String answer4 = "";
static String correctanswer = "";
#Override
public void onCreate(Bundle savedInstanceState) {
// Get any saved data
super.onCreate(savedInstanceState);
// Point to the name for the layout xml file used
setContentView(R.layout.main);
// Call for doInBackground() in MyAsyncTask to be executed
new MyAsyncTask().execute();
}
// Use AsyncTask if you need to perform background tasks, but also need
// to change components on the GUI. Put the background operations in
// doInBackground. Put the GUI manipulation code in onPostExecute
private class MyAsyncTask extends AsyncTask<String, String, String> {
protected String doInBackground(String... arg0) {
// HTTP Client that supports streaming uploads and downloads
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
// Define that I want to use the POST method to grab data from
// the provided URL
HttpPost httppost = new HttpPost(dlquiz);
// Web service used is defined
httppost.setHeader("Content-type", "application/json");
// Used to read data from the URL
InputStream inputStream = null;
// Will hold the whole all the data gathered from the URL
String result = null;
try {
// Get a response if any from the web service
HttpResponse response = httpclient.execute(httppost);
// The content from the requested URL along with headers, etc.
HttpEntity entity = response.getEntity();
// Get the main content from the URL
inputStream = entity.getContent();
// JSON is UTF-8 by default
// BufferedReader reads data from the InputStream until the Buffer is full
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
// Will store the data
StringBuilder theStringBuilder = new StringBuilder();
String line = null;
// Read in the data from the Buffer untilnothing is left
while ((line = reader.readLine()) != null)
{
// Add data from the buffer to the StringBuilder
theStringBuilder.append(line + "\n");
}
// Store the complete data in result
result = theStringBuilder.toString();
} catch (Exception e) {
e.printStackTrace();
}
finally {
// Close the InputStream when you're done with it
try{if(inputStream != null)inputStream.close();}
catch(Exception e){}
}
//Log.v("JSONParser RESULT ", result);
try {
JSONArray array = new JSONArray(result);
for(int i = 0; i < array.length(); i++)
{
JSONObject obj = array.getJSONObject(i);
//now, get whatever value you need from the object:
placename = obj.getString("placename");
latitude = obj.getString("latitude");
longitude = obj.getString("longitude");
question = obj.getString("question");
answer1 = obj.getString("answer1");
answer2 = obj.getString("answer2");
answer3 = obj.getString("answer3");
answer4 = obj.getString("answer4");
correctanswer = obj.getString("correctanswer");
}
} catch (JSONException e){
e.printStackTrace();
}
return result;
}
protected void onPostExecute(String result){
// Gain access so I can change the TextViews
TextView line1 = (TextView)findViewById(R.id.line1);
TextView line2 = (TextView)findViewById(R.id.line2);
TextView line3 = (TextView)findViewById(R.id.line3);
// Change the values for all the TextViews
line1.setText("Place Name: " + placename);
line2.setText("Question: " + question);
line3.setText("Correct Answer: " + correctanswer);
}
}
}
Instead of keeping variables:
static String placename = "";
static String latitude = "";
static String longitude = "";
static String question = "";
static String answer1 = "";
static String answer2 = "";
static String answer3 = "";
static String answer4 = "";
static String correctanswer = "";
make Bean Class having all these variables. Make array list of bean and during parsing make bean objects and add to list.
Bean Class:
public class ModelClass{
private String latitude = "";
private String longitude = "";
private String question = "";
private String answer1 = "";
private String answer2 = "";
private String answer3 = "";
private String answer4 = "";
private String correctanswer = "";
// ....
// Getter Setters and constructors
// .......
}
ArrayList<ModelClass> mList=new ArrayList<ModelClass>();
In for loop of json parsing:
JSONObject obj = array.getJSONObject(i);
ModelObject object=new ModelObject();
// parse and make ModelObject
list.add(object);
Try using this approach. It will work.
you should divide your objects into classes, and use the GSON json parser.
look at this answer on how to parse a json array into objects:
JSON parsing using Gson for Java
a good approach would be a class question that contains a list of subclasses called possibleanswers, those have a boolean attribute ( correct : true, incorrect: false) to check if the user has clicked the correct one.
if you want to store the data, you will have to use sqllite or any of the many libraries like ActiveAndroid.
I see that you are accessing this JSON file form a Remote Service. On that basis, you will need to structure your code in a manner that will work around how many instances are in the physical JSON file.
Your issue is here:
JSONArray array = new JSONArray(result);
for(int i = 0; i < array.length(); i++)
{
JSONObject obj = array.getJSONObject(i);
You are telling it that the entire JSON file has an array, which contains a length, which is incorrect.
Curly Brackets ("{") represent a JSONObject, and Square Brackets ("[") represent a JSON Array.
Based on your JSON file:
[
{
"placename": "place1",
"latitude": "50",
"longitude": "-0.5",
"question": "place1 existed when?",
"answer1": "1800",
"answer2": "1900",
"answer3": "1950",
"answer4": "2000",
"correctanswer": "1900"
},
You are dealing with one JSONArray, and this array has to no reference name give to it, rather a place index.
Heres what you need to try:
public class ListCreator{
private List<String> placename;
public ListCreator() {
placename = new ArrayList<String>();
}
public void addPlaceName(String s)
{
answers.add(s);
}
public String[] getAnswers()
{
return placename.toArray(new String[1]);
}
}
Bear in mind that is just a snippet of what the class will look like only for the "placename" fields.
Now to your JSON:
You will need to initialize a Vector Variable for each List you want to create:
private Vector<ListCreator> placeNameVec;
Next you will need to set a method for each part of the JSONArray:
public Vector getPlaceNames(){
return placeNameVector;
}
JSONArray array = new JSONArray(result);
for(int x = 0; x < 3; x++){
JSONObject thisSet = array.getJSONObject(x);
ListCreator placeNames = new ListCreator();
placeNames.addPlaceName(thisSet.getString("placename"));
}
placeNameVec.add(placeNames);
That should get you going on what you are trying to answer.
So basically bear in mind that you you can't specify the "array.length()".
Hope this helps!
Please let me know of the outcome :)
If you get into any further difficulty, this Tutorial on JSONParsing really did help me when I was confused.
All the best
I have a jersey client that is getting JSON from a source that I need to get into properly formatted JSON:
My JSON String looks like the folllowing when grabbing it via http request:
{
"properties": [
{
someproperty: "aproperty",
set of data: {
keyA: "SomeValueA",
keyB: "SomeValueB",
keyC: "SomeValueC"
}
}
]
}
I am having problems because the json has to be properly formatted and keyA, keB, and keyC are not surrounded in quotes. Is there some library that helps add quotes or some best way to go about turning this string to properly formatted json? Or if there is some easy way to convert this to a json object without writing a bunch of classes with variables and lists that match the incoming structure?
you can use json-lib. it's very convenient! you can construct your json string like this:
JSONObject dataSet = new JSONObject();
dataSet.put("keyA", "SomeValueA") ;
dataSet.put("keyB", "SomeValueB") ;
dataSet.put("keyC", "SomeValueC") ;
JSONObject someProperty = new JSONObject();
dataSet.put("someproperty", "aproperty") ;
JSONArray properties = new JSONArray();
properties.add(dataSet);
properties.add(someProperty);
and of course you can get your JSON String simply by calling properties.toString()
I like Flexjson, and using lots of initilizers:
public static void main(String[] args) {
Map<String, Object> object = new HashMap<String, Object>() {
{
put("properties", new Object[] { new HashMap<String, Object>() {
{
put("someproperty", "aproperty");
put("set of dada", new HashMap<String, Object>() {
{
put("keyA", "SomeValueA");
put("keyB", "SomeValueB");
put("keyC", "SomeValueC");
}
});
}
} });
}
};
JSONSerializer json = new JSONSerializer();
json.prettyPrint(true);
System.out.println(json.deepSerialize(object));
}
results in:
{
"properties": [
{
"someproperty": "aproperty",
"set of dada": {
"keyA": "SomeValueA",
"keyB": "SomeValueB",
"keyC": "SomeValueC"
}
}
]
}
Your string isn't JSON. It's something that bears a resemblance to JSON. There is no form of JSON that makes those quotes optional. AFAIK, there is no library that will reads your string and cope with the missing quotes and then spit it back out correctly. You need to find the code that produced this and repair it to produce actual JSON.
You can use argo, a simple JSON parser and generator in Java