Dart Parse JSON into Table - java

I'm trying to figure out how to parse a JSON feed into a table in Dart. I'm not sure if I should use a Map but if I do, I'm not sure how to approach extracting data. I want to have one cell to hold the assetID, then another for domain name, and another for IP address. Please let me know if you need more information.
Dart:
void loadData()
{
var url = "http://localhost:8080/***selectAll";
//call the web server asynchronously
var request = HttpRequest.getString(url).then(onDataLoaded);
}
void onDataLoaded(String response)
{
TableElement table = querySelector("#domainTableSelector");
//table.children.add();
var jsonString = response;
// print(jsonString);
List<String> list = new List<String>();
list.add(jsonString);
for (var x = 0; x < list.length; x++)
{
//create new table row
TableRowElement row = table.insertRow(x+1);
TableCellElement cell = row.insertCell(x);
cell.text = list.toString();
// print(list);
}
// Iterator itr= list.iterator();
//
// print("Displaying List Elements,");
//
// while(itr.hasNext())
// {
// print(itr.next());
// }
}
JSON
[{"serviceResponseValue":[{"assetId":"8a41250446b89b5f0146b04d49910023","oplock":0,"longitude":115.86,"domainName":"free-aus-trip.au","latitude":-31.95,"ipAddress":"6.0.0.6"},{"assetId":"8a49859246918966014691b1aac9000c","oplock":0,"longitude":-65.30,"domainName":null,"latitude":-24.18,"ipAddress":"4.0.0.4"},{"assetId":"8a49859246876566014691b1437512e4","oplock":0,"longitude":77.60,"domainName":"allmovies.cn","latitude":12.97,"ipAddress":"14.0.0.14"},{"assetId":"8a49850446b04b5f0146b04d49910000","oplock":0,"longitude":112.47,"domainName":"getrichez.cn","latitude":32.98,"ipAddress":"5.0.0.5"},{"assetId":"8a498592469189660146919b7a210006","oplock":0,"longitude":-37.61,"domainName":"googles.com","latitude":55.75,"ipAddress":null},{"assetId":"8a42250876b89b5f0876b04d49910763","oplock":0,"longitude":-68.90,"domainName":"lolcatzfun.net","latitude":-22.48,"ipAddress":"8.0.0.8"},{"assetId":"8a498592469189660146919f8d700008","oplock":0,"longitude":113.50,"domainName":"ccn.com","latitude":52.03,"ipAddress":null},{"assetId":"8a45250446b89b5f0876b04d49910187","oplock":0,"longitude":115.84,"domainName":"free-aus-trip.au","latitude":-31.86,"ipAddress":"7.0.0.7"},{"assetId":"8a49859246918966014691aeda76000a","oplock":0,"longitude":3.38,"domainName":"cashnow.net","latitude":6.52,"ipAddress":"2.0.0.2"},{"assetId":"8a49859246918966014691ae19df0009","oplock":0,"longitude":7.48,"domainName":"free-money.tv","latitude":9.07,"ipAddress":"222.222.222.222"},{"assetId":"8a498592469189660146919e09900007","oplock":0,"longitude":30.34,"domainName":"facebok.com","latitude":59.93,"ipAddress":"111.111.111.222"},{"assetId":"8a49859246918966014691b14375000b","oplock":0,"longitude":116.41,"domainName":null,"latitude":39.90,"ipAddress":"0.0.0.111"}],"messages":{"messages":[]}}]

To work with JSON, you have in dart a great thing : dart:convert => JSON
here some example of use:
var encoded = JSON.encode([1, 2, { "a": null }]);
var decoded = JSON.decode('["foo", { "bar": 499 }]');
I have done some thing but i'm not sure that is fit perfectly with your need
import 'dart:html';
import 'dart:convert';
void loadData()
{
var url = "http://localhost:8080/***selectAll";
//call the web server asynchronously
var request = HttpRequest.getString(url).then(onDataLoaded);
}
void onDataLoaded(String response)
{
TableElement table = querySelector("#domainTableSelector");
//table.children.add();
var jsonString = response;
// print(jsonString);
var jsonObject = JSON.decode(jsonString);
for (var x = 0; x < jsonObject.length; x++)
{
//create new table row
TableRowElement row = table.insertRow(x+1);
for (var d in jsonObject[x]["serviceResponseValue"]) {
TableCellElement cell = row.insertCell(x);
cell.text = d["assetId"];
cell = row.insertCell(x);
cell.text = d["domainName"];
cell = row.insertCell(x);
cell.text = d["ipAddress"];
print(d["assetId"]);
print(d["domainName"]);
print(d["ipAddress"]);
}
// print(list);
}
}

You parse JSON into a Dart data structure using
import 'dart:convert' show JSON;
var decoded = JSON.decode(jsonString);
see also How to handle JSON in Dart (Alexandres answer)
decoded is then a Dart data structure (lists, maps, values) that you can iterate over or investigate in the debugger. If you need further assistance please add a comment.

Related

Passing a String[] from react to springboot

I want to pass a String array of usernames from react to Spring so that I can then get some user details for each of those usernames and finally pass this back to react as a List<String>
So far in react, I am making an array of usernames, and then passing them as the request body to spring
const roundRobin = () => {
const userList = []
//Get list of entrants usernames to pass to backend
for(let i = 0; i < entrants.length; i++){
userList.push(entrants[i].username);
console.log(userList);
}
const List = JSON.stringify(userList)
//API call
apiCalls
.getRandomUserList(List)
.then((response) => {
console.log(response.data);
})
.catch((apiError) => {
if (apiError.response.data && apiError.response.data.validationErrors) {
setEditErrors(apiError.response.data.validationErrors);
}
console.log(apiError.response.data)
setPendingApiCall(false);
});
}
In spring my controller takes the request body as a String[]
//create a random list of members who have entered an event
#CrossOrigin
#GetMapping("/users/createRandomList")
List<String> randomList(#RequestBody String[] usernames) {
return userService.createRandomUserList(usernames);
}
The UserService then takes the String[] and changes it to a List and calls a method which randomly rearranges the order of the Strings, it then loops through the returned List (which are a username) and gets the User from the database and adds some details about that User to a new List This is then returned to react.
public List<String> createRandomUserList(String[] randomUsernames) {
List<String> users = new ArrayList<>();
List<String> randomUsersList = Arrays.asList(randomUsernames);
List<String> randomUsers = getRandomUsers(randomUsersList);
for (String randUsernames : randomUsers) {
User u = userRepository.findByUsername(randUsernames);
users.add(u.getFirstname() + " " + u.getSurname() + " " + u.getHandicap());
}
return users;
}
//Create list of entrants IDs in random order for tee times.
public List<String> getRandomUsers(List<String> userIds) {
int size = userIds.size();
List<String> passedList = userIds;
List<String> entrants = new ArrayList<>();
Random rand = new Random();
for(int i = 0; i < size; i++) {
int randomIndex = rand.nextInt(passedList.size());
entrants.add(passedList.get(randomIndex));
passedList.remove(randomIndex);
}
return entrants;
}
When I try and run this in my web app though, I get an HTTP 400 error,
{timestamp: 1640902047907, status: 400, message: 'Required request body is missing: java.util.List<j…ser.UserController.randomList(java.lang.String[])', url: '/api/1.0/users/createRandomList'}
I am not sure what I am doing wrong, as far as I can tell, I am passing an array to Spring, when I console.log(List), I get ["user1","user2"]
I think you should change the get mapping to post mapping and then use the List instead of String[], try in that way
#CrossOrigin
#GetMapping("/users/createRandomList")
List<String> randomList(#RequestBody List<String> usernames) {
return userService.createRandomUserList(usernames);
}
also change service methods according to the changes

Use string values from an array as string variable to parse json - codenameone

I have a no. of checkboxes (20), what i did is if a user select any checkbox, its name is stored in an array (eg abc array below in code). The name of the string variable that stores the respective json is of the same name as of the checkbox. For eg if Checkbox "a" is clicked, string value "a" is stored in array and there is a string variable named "a" that stores the related json values. What I need is that if i pass the string value stored in array as InputStream is = new ByteArrayInputStream(abc.get(i).getBytes()), it should be used to parse the inputStream for json. But it gives NullPointerException since the string value "a" is not equal to string variable a. How can i solve this problem? I ran out of ideas here. Is there other ways to achieve what i want to do here?
code: String values of the selected checkboxes are stored in an array
String a = "[{\n"
+ "\t\t\t\"title\": \"title1\",\n"
+ "\t\t\t\"describ\": \"describ1\"\n"
+ "}]";
String b = "[{\n"
+ "\"title\": \"title2\",\n"
+ "\"describ\": \"describ2\"\n"
+ "}]";
String c = "[{\n"
+ "\t\t\t\"title\": \"title3\",\n"
+ "\t\t\t\"describ\": \"describ3\"\n"
+ "}]";
//and all jsons required are there
ArrayList<String> abc;
#Override
protected void beforeTestForApp(Form f) {
f.setTitle("abc");
abc = new ArrayList<>();
//I have stored "a" & "b" in the abc array here for simplicity, but it is dynamic,
//ie. if the user select checkbox c, c will be stored in abc array and so on
abc.add("a");
abc.add("b");
Button bb = new Button("go");
bb.addActionListener((e) -> {
showForm("TestForAppResult", null);
});
f.add(bb);
}
Form for json parser and displaying the values:
#Override
protected void beforeTestForAppResult(Form f) {
f.setLayout(new BoxLayout(BoxLayout.Y_AXIS));
InputStream is;
for (int i = 0; i < abc.size(); i++) {
Label heading = new Label(abc.get(i));
f.add(heading);
//this gives error since abc.get(i) gives string value, not string variable
is = new ByteArrayInputStream(abc.get(i).getBytes());
showDetails(is, f);
}
//if i do this instead of for loop jst above, i can get the result but since what value'll be stored in an array is not known,it is not possible
//is = new ByteArrayInputStream(a.getBytes());
//showDetails(is, f);
//is = new ByteArrayInputStream(b.getBytes());
//showDetails(is, f);
}
private void showDetails(InputStream is, Form f) {
JSONParser p = new JSONParser();
Hashtable<String, Object> test;
try {
test = p.parse(new InputStreamReader(is));
Vector aVector = (Vector) test.get("root");
for (int j = 0; j < aVector.size(); j++) {
Hashtable hm = (Hashtable) aVector.get(j);
String title = (String) hm.get("title");
String describ = (String) hm.get("describ");
Label z = new Label(title);
Label zz = new Label(describ);
f.add(z);
f.add(zz);
}
} catch (IOException ex) {
}
}
tbh i didnt get your problem concretely but i still try to give you some shots so you can try out.
If i understand correctly you have 20 objects which contains values underlying?
So then you have a JSONArray, just iterate trough it and grab that JSONObject.
now just use parseJSON instead of parse as it is deprecated...
here is a short snippet of my code
JSONArray jsonTasks = new JSONArray(responseString);
for (int index = 0; index < jsonTasks.length(); index++) {
JSONObject jsonObject = (JSONObject) jsonTasks.get(index);
if (jsonObject != null) {
Map jsonMap = new JSONParser().parseJSON(new InputStreamReader(new ByteArrayInputStream(jsonObject.toString().getBytes(UTF8)), UTF8));
System.out.println(jsonMap.get("date"));

Why the data is going as null in my test and how to convert it data provider data as per my function in java

I have read some data from Excel in array form, and converted into a 2-D array in order to provide the data to a data provider.But now in the #Test when I pass the data it takes on the null value.
Can you please suggest why it's going null? Also my function in #Test is using a map as well - how can I convert the data provider data to map ?
My function in #Test is like below:-
public void testCategorySearch(String vendor_code, Map<Integer, List<String>> seller_sku , String upload_id,Protocol protocol)
throws InvocationTargetException
My code is :
#DataProvider(name = "valid_parameters")
public Object[][] sendValidParameters() {
List<ArrayList> result = td.getExcelData("C:\\Users\\ashish.gupta02\\QAAutomation\\test.xls", 1);
Object[][] a = new String[result.size()][3];
{
for (int i = 0; i < result.size(); i++) {
Object currentObject = result.get(i);
a[i][0] = currentObject.toString();
System.out.println("COnverted" + a[i][0]);
}
}
System.out.println("Printing data" + a);
//return mapper.getProtocolMappedObject(a);
//return Object ;
return a;
}
#Test(dataProvider = "valid_parameters", groups = {"positive"})
public void testCategorySearch(String vendor_code, Map<Integer, List<String>> seller_sku, String upload_id, Protocol protocol)
throws InvocationTargetException {
//Protocol protocol
//set parameter values to the api
System.out.println("Executing the request");
CreateSellerProductUpdateInfoRequest createReq = setRequest(vendor_code, seller_sku, upload_id, protocol);
CreateSellerProductUpdateInfoResponse createResponse = service.createSellerProductUpdateInfo(createReq);
System.out.print("Response is :" + createResponse);
}

Loop Array to Plot Marker

I have a JSON with an array of 3 objects. So when I retrieveEventJSON(), I am simply setting the attributes to an Event object. And when I call the plotEventOnMap() from another activity, I expect to see 3 markers on the map.
public void retrieveEventJSON() throws JSONException {
String page;
JSONArray jsonArray;
try {
// Code to retrieve data from servlet
try {
JSONObject jsonObject = new JSONObject(page);
jsonArray = jsonObject.getJSONArray("Events");
int length = jsonArray.length();
for (int i = 0; i < length; i++) {
JSONObject attribute = jsonArray.getJSONObject(i);
String eventID = attribute.getString("eventID");
String eventName = attribute.getString("eventName");
String eventDesc = attribute.getString("eventDesc");
String eventDate = attribute.getString("eventDate");
eventModel.setEventID(eventID);
eventModel.setEventName(eventName);
eventModel.setEventDesc(eventDesc);
eventModel.setEventDate(eventDate);
}
} catch (JSONException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void plotEventOnMap(Context context) {
graphicIcon = new PictureMarkerSymbol(res);
Point p = new Point(Double.parseDouble(eventModel.getEventX()),
Double.parseDouble(eventModel.getEventY()));
Symbol symbol = graphicIcon;
HashMap<String, Object> attrMap = new HashMap<String, Object>();
attrMap.put("eventName", eventModel.getEventName());
attrMap.put("eventBy", eventModel.getEventBy());
ENeighbourhoodActivity.graphicsLayer.addGraphic(new Graphic(p, symbol,
attrMap));
}
But with these codes, it just display the last row of record in my JSON instead of looping and plot each of them. Any guides?
Thanks in advance.
You need to call .plotEventOnMap(), or otherwise do something with the EventModel you've constructed, from inside your loop, after setting all the EventModel properties. At the moment, you're just overwriting your EventModel without ever using it.
for (int i = 0; i < length; i++) {
JSONObject attribute = jsonArray.getJSONObject(i);
String eventID = attribute.getString("eventID");
String eventName = attribute.getString("eventName");
String eventDesc = attribute.getString("eventDesc");
String eventDate = attribute.getString("eventDate");
eventModel.setEventID(eventID);
eventModel.setEventName(eventName);
eventModel.setEventDesc(eventDesc);
eventModel.setEventDate(eventDate);
}
Just before the loop ends, you need to do something with the EventModel you've now constructed. This might be plotting it, or adding it to some collection, or whatever. But at the moment, you're going straight back into the loop, and then in the next iteration, overwriting all the good work you've done. The reason you're only ending up with the last one is that when you've done the last iteration, what's left in eventModel is what you wrote the last time you went through the loop.
In fact I think you also want
EventModel eventModel = new EventModel();
as the first thing inside your loop. (I don't know if this is exactly right because we haven't seen the code for EventModel so I don't know what the constructor looks like.) If you want to keep a List (or similar) of all of them, you need to make sure they're all different instances.
I would suggest recasting like this:
List<EventModel> events = new ArrayList<EventModel>(); //NEW
for (int i = 0; i < length; i++) {
EventModel eventModel = new EventModel(); //NEW
JSONObject attribute = jsonArray.getJSONObject(i);
String eventID = attribute.getString("eventID");
String eventName = attribute.getString("eventName");
String eventDesc = attribute.getString("eventDesc");
String eventDate = attribute.getString("eventDate");
eventModel.setEventID(eventID);
eventModel.setEventName(eventName);
eventModel.setEventDesc(eventDesc);
eventModel.setEventDate(eventDate);
events.add(eventModel); //NEW
}
After the loop has finished, you'll have a list of EventModels that you can send to your plotting method or whatever's appropriate.
eventModel.setEventName(eventName); returns the latest element added to it because on every iteration you are resetting it.
You may add the object to the list after each iteration so that the list will have the elements. Declare the your EventModel object inside the for loop to have the instance for every iteration.
for (int i = 0; i < length; i++) {
JSONObject attribute = jsonArray.getJSONObject(i);
String eventID = attribute.getString("eventID");
String eventName = attribute.getString("eventName");
EventModel eventModel=new eventModel();
eventModel.setEventID(eventID);
eventModel.setEventName(eventName);
list.add(eventModel);
}

Show cell data within listFilesInFolder Function

I have this formula, which successfully lists all of my files in a folder. Awesome. But, can I also, within this script list some specific cell data from each file?
function listFilesInFolder() {
var folder = DocsList.getFolder("1- Summaries");
var contents = folder.getFiles();
var file;
var data;
var sheet = SpreadsheetApp.getActiveSheet();
sheet.clear();
sheet.appendRow(["Name", "Date", "Size", "URL", "Download", "Description", "Type"]);
for (var i = 0; i < contents.length; i++) {
file = contents[i];
if (file.getFileType() == "SPREADSHEET") {
continue;
}
data = [
file.getName(),
file.getDateCreated(),
file.getValue(B10), **(THIS IS WHERE I WOULD LIKE TO GET DATA, but it does not work)**
file.getUrl(),
"https://docs.google.com/a/acme.com/spreadsheet/ccc?key=" + file.getId(),
file.getDescription(),
"audio/mp3"
]
sheet.appendRow(data);
You can read from the spreadsheet, yes.
In the place where if (file.getFileType()... is, put this:
var cellValue;
if (file.getFileType() === "SPREADSHEET") {
cellValue = SpreadsheetApp.openById(file.getId()).getSheetByName("NameOfSheet")
.getRange("B10").getValue();
} else {
cellValue = null; // specify some default value here!
}
...
Then in your data array:
data = [
file.getName(),
file.getDateCreated(),
cellValue,
...

Categories

Resources