I'm having trouble having Processing (v.3.0.1) to read a JSON file, I get back the error on the title.
This is part of the JSON file (minus several hundred objects similar to the ones I show):
{
"matches":[
{
"p1":{
"reds":0,
"team":"Liverpool",
"goals":1
},
"p2":{
"reds":0,
"team":"Bayern Munich",
"goals":2
},
"match":1
},
{
"p1":{
"reds":0,
"team":"Psg",
"goals":3
},
"p2":{
"reds":1,
"team":"Manchester City",
"goals":0
},
"match":2
}
]
}
And this is the Processing sketch where I try to read the JSON file:
String filename = "data.json";
JSONObject json;
Match[] matches;
Player[] allPlayers;
void setup(){
loadData();
size(600,300);
}
void draw(){
background(40);
}
void loadData(){
json = loadJSONObject(filename); // This is where the error happens
JSONArray matchesData = json.getJSONArray("matches");
matches= new Match[matchesData.size()];
for(int i=0; i<matchesData.size(); i++){
JSONObject match = matchesData.getJSONObject(i);
JSONObject p1 = matchesData.getJSONObject(0);
String p1Team = p1.getString("team");
int p1Goals = p1.getInt("goals");
int p1Reds = p1.getInt("reds");
JSONObject p2 = matchesData.getJSONObject(1);
String p2Team = p2.getString("team");
int p2Goals = p2.getInt("goals");
int p2Reds = p2.getInt("reds");
int matchNum = match.getInt("match");
allPlayers[0] = new Player("p1", p1Team, p1Goals, p1Reds);
allPlayers[1] = new Player("p2", p2Team, p2Goals, p2Reds);
matches[i] = new Match(matchNum, allPlayers[0], allPlayers[1]);
}
}
Related
I'm using asyncHTTPrequest for async request to a REST API in ESP8266.
I receive the response in JSON format but can't parse it.
This kind of parsing was working while i used to made sync call to API.
I tried to store the request->responseText() into a String variable because its return a String, but the variable never get any value.
void sendRequest() {
if (request.readyState() == 0 || request.readyState() == 4) {
request.open("GET", "http://192.168.1.103:45456/api/systems/1013/arduino");
request.send();
}
}
void requestCB(void* optParm, asyncHTTPrequest* request, int readyState) {
if (readyState == 4) {
Serial.println(request->responseText());
const size_t capacity = JSON_ARRAY_SIZE(1) + JSON_ARRAY_SIZE(2) + JSON_OBJECT_SIZE(2) + 2*JSON_OBJECT_SIZE(4) + JSON_OBJECT_SIZE(8)+816;
DynamicJsonBuffer jsonBuffer(capacity);
JsonObject& root = jsonBuffer.parseObject(request->responseText());
String a = request->responseText();
Serial.println(a);
JsonObject& schState = root["dataForArduino"][0];
String beginTime = schState["start"]; // "2019-12-02T21:51:00"
}
}
void setup() {
Serial.begin(9600);
wifi.Connect();
request.onReadyStateChange(requestCB);
ticker.attach(5, sendRequest);
}
I have wrote json parsing function (__get_from_json) to get key value from json here
e.g. if you have json response like
{
"timestamp" : "2020-04-01 19:20:49"
}
and in your application you want to parse timestamp value from it then
char response[max_response_size] = "{ \"timestamp\" : \"2020-04-01 19:20:49\" }";
char key[max_key_size] = "timestamp";
char value[max_value_size] = "";
if( __get_from_json( response, key, value, max_value_size ) ){
Serial.println(value);
}
I had the same problem and added .c_str() to get the response to print.
So in your example it would be:
String a = request->responseText();
Serial.println(a.c_str());
For the JSON I also needed to add .c_str()
DynamicJsonDocument jsonDoc(2048);
DeserializeJson(jsonDoc, a.c_str());
I'm currently working on my final project for my university, but unfortunately I stopped in this part, because I tried several things like trying to pass a variable with a list inside from servlet to a jsp file to use in a json function from a project https://gist.github.com/smrchy/7040377 and render a tree.
Right now my project I render directly from a sql query which is not ordered and don't show the relationship.
right now
I created a constructor to create a array or list with the values and parameters in java class, when i try to send it through session or parameter doesn't work...
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession sessao = request.getSession(false);
response.setContentType("application/json");
try {
FicheiroDAO x = new FicheiroDAO();
x.imprime();
List<Ficheiro> lista = x.getLista();
JSONObject json;
JSONArray addresse = new JSONArray();
JSONObject listas = new JSONObject();;
try {
for (int i = 0; i < lista.size(); i++) {
json = new JSONObject();
json.put("id", lista.get(i).getId());
json.put("parentid", lista.get(i).getPasta());
json.put("name", lista.get(i).getNome());
addresse.put(i, json);
}
} catch (JSONException jse) {
}
String s = addresse.toString();
request.setAttribute("listagem", s);
sessao.setAttribute("listagem", s);
sessao.setAttribute("teste", "POST");
request.setAttribute("teste", "POST");
request.getRequestDispatcher("files.jsp").forward(request, response);
My sql engine is Mysql and the image showing the table of the files is on my comment where the id_pasta it's the parent of the file
So I stopped trying that way and right now I'm trying to run the select in the JSP using java JSTL to create the array.
So I need some help from you experts to know the best way and easier to show correctly what I pretend.
Many thanks and regards!
EDITED FOR MORE INFO:
The way I want to show is like this
one
two
four
three
five
six
So in that way I can display in a easy way what I want...
Edited:
Failed try to save the information from result set query, any ideas?
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://192.168.1.98:3306/repual", "admin", "123");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select id_fich, nome_fich, tipo_fich, id_pasta from repual.ficheiro join repual.permissoes where (id_fich=id_ficheiro) and (id_utilizador='26' or dep like ('%'+'1'+'%')) and id_pasta!=2 order by nome_fich");
Gson gson = new Gson();
Map<String, String> objeto = new HashMap<String, String>();
ArrayList data = new ArrayList();
while (rs.next())
{
Map<String, String> lv = new HashMap<String, String>();
lv.put("id", rs.getString("id_fich"));
lv.put("parentid", rs.getString("id_pasta"));
lv.put("name", rs.getString("nome_fich"));
data.add(lv);
}
//create 'dataMap' map object to make a complete FC datasource.
Map<String, String> dataMap = new LinkedHashMap<String, String>();
/*
gson.toJson() the data to retrieve the string containing the
JSON representation of the data in the array.
*/
JsonObject object = new JsonObject();
String json = gson.toJson(data);
con.close();
New update:
I changed the way to do, and I'm now trying this new way but unfortunately I can't get the array from the "scriptlet" into javascript to use in the methods already created.
Here is the code, can someone help me how Can I use the Json array in json code (javascript)?
I created the variable status to receive the array but no luck even testing the string sd to receive the value, so my idea was use the the array "arr" created from resultset to replace the array "sqlquery" manually created in javascript and use the functions to output the elements..
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<%#page import="org.json.JSONException"%>
<%#page import="org.json.JSONArray"%>
<%#page import="org.json.JSONObject"%>
<%#page import="java.sql.*" %>
<%#page import="java.util.*" %>
<%#page import="com.google.gson.*" %>
<%# taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c"%>
<%# taglib uri = "http://java.sun.com/jsp/jstl/sql" prefix = "sql"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%
HttpSession sessao = request.getSession(false);
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
String myVar = "sadsa";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/repual", "root", "admin");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select id_fich, nome_fich, tipo_fich, id_pasta from repual.ficheiro join repual.permissoes where (id_fich=id_ficheiro) and (id_utilizador='26' or dep like ('%'+'1'+'%')) and id_pasta!=2 order by nome_fich");
Gson gson = new Gson();
JSONArray arr = new JSONArray();
while (rs.next())
{
JSONObject obj = new JSONObject();
obj.put("id", rs.getString("id_fich"));
obj.put("parentid", rs.getString("id_pasta"));
obj.put("name", rs.getString("nome_fich"));
arr.put(obj);
}
con.close();
st.close();
out.println(arr.toString());
String sd = "asdsad";
%>
<h1>SQL Query to Tree</h1>
<h3>The SQL query</h3>
select id_fich, nome_fich, tipo_fich, id_pasta from ficheiro join permissoes where (id_fich = id_ficheiro) and (id_utilizador = '26' or dep like ('%' + '1' + '%')) and id_pasta != 2 order by nome_fich
<pre id="sqlquery"></pre>
<h3>The sorted query</h3>
<pre id="sortedquery"></pre>
<h3>The Tree</h3>
<pre id="tree"></pre>
<h3>HTML List</h3>
<div id="htmllist"></div>
<button type="button" onclick="downloadficheiro();">sadsaad</button>
<button type="button" onclick="downloadficheir();">post</button>
<!-- jQuery 3 -->
<script src="bower_components/jquery/dist/jquery.min.js"></script>
</body>
</html>
<script type="text/javascript">
var _queryTreeSort = function (options) {
var cfi, e, i, id, o, pid, rfi, ri, thisid, _i, _j, _len, _len1, _ref, _ref1;
id = options.id || "id";
pid = options.parentid || "parentid";
ri = [];
rfi = {};
cfi = {};
o = [];
_ref = options.q;
for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
e = _ref[i];
rfi[e[id]] = i;
if (cfi[e[pid]] == null) {
cfi[e[pid]] = [];
}
cfi[e[pid]].push(options.q[i][id]);
}
_ref1 = options.q;
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
e = _ref1[_j];
if (rfi[e[pid]] == null) {
ri.push(e[id]);
}
}
while (ri.length) {
thisid = ri.splice(0, 1);
o.push(options.q[rfi[thisid]]);
if (cfi[thisid] != null) {
ri = cfi[thisid].concat(ri);
}
}
return o;
};
var _makeTree = function (options) {
var children, e, id, o, pid, temp, _i, _len, _ref;
id = options.id || "id";
pid = options.parentid || "parentid";
children = options.children || "children";
temp = {};
o = [];
_ref = options.q;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
e = _ref[_i];
e[children] = [];
temp[e[id]] = e;
if (temp[e[pid]] != null) {
temp[e[pid]][children].push(e);
} else {
o.push(e);
}
}
return o;
};
var _renderTree = function (tree) {
var e, html, _i, _len;
html = "<ul>";
for (_i = 0, _len = tree.length; _i < _len; _i++) {
e = tree[_i];
html += "<li>" + e.name;
if (e.children != null) {
html += _renderTree(e.children);
}
html += "</li>";
}
html += "</ul>";
return html;
};
sqlquery = ([
{"id": "456", "parentid": "123", "name": "Dogs"},
{"id": 214, "parentid": 456, "name": "Labradors"},
{"id": 123, "parentid": 0, "name": "Mammals"},
{"id": 810, "parentid": 456, "name": "Pugs"},
{"id": 919, "parentid": 456, "name": "Terriers"}
]);
var status = document.getElementsByName("arr");
$('#sqlquery').html(JSON.stringify(sqlquery, true, 2));
sortedquery = _queryTreeSort({q: sqlquery})
$('#sortedquery').html(JSON.stringify(sortedquery, true, 2));
tree = _makeTree({q: sortedquery})
$('#tree').html(JSON.stringify(tree, true, 2));
htmllist = _renderTree(tree)
$('#htmllist').html(htmllist);
function downloadficheir() { // Eliminar uma pasta ou ficheiro
var f = document.form;
f.method = "post";
f.action = 'listaficheiro ';
f.submit();
}
function downloadficheiro() { // Eliminar uma pasta ou ficheiro
var f = document.form;
f.method = "get";
f.action = 'abreficheiro';
f.submit();
}
foo();
function foo()
{
var value = $('#sd').val();
alert(value);
}
</script>
I am trying to use the string in a variable to create an item in an object.
Example non functioning code:
private var myName:String = 'group1';
private var _ins:Object = {
myName : {
data1: arr[0],
data2: arr[1]
}
}
I can not understand what syntax to use to make myName be 'group1' text. Currently I am using:
private var _ins:Object = {
'group1' : {
data1: arr[0],
data2: arr[1]
}
}
Syntax of generic objects in AS3 allow to omit quotes for the keys, but actually your code is:
private var myName:String = 'group1';
private var _ins:Object = {
"myName" : {
"data1": arr[0],
"data2": arr[1]
}
}
You should use myName as a variable, which contains a key.
private var myName:String = 'group1';
private var _ins:Object = {};
_ins[myName] = {
data1: arr[0],
data2: arr[1]
};
I am developing a ASP.NET MVC Web Api. Project. I am returning data with JSON format. Before I return data to user I serialize data using JsonConvert.SerializeObject to change their json property names.My code return data in JSON format. But with an issue. That is it always return data into string even if the data is array or object.
This is my action method that returns json.
public HttpResponseMessage Get()
{
IEnumerable<Region> dbRegions = regionRepo.GetCachedRegions();
List<ContentRegion> regions = new List<ContentRegion>();
if(dbRegions!=null && dbRegions.Count()>0)
{
foreach(var region in dbRegions)
{
ContentRegion contentRegion = new ContentRegion
{
Id = region.Id,
ImageUrl = Url.AbsoluteContent(region.ImagePath),
SmallImageUrl = (String.IsNullOrEmpty(region.ImagePath))?null:Url.AbsoluteContent(CommonHelper.GetImageUrl(region.ImagePath,AppConfig.SmallThumbSuffix)),
MediumImageUrl = (String.IsNullOrEmpty(region.ImagePath))?null:Url.AbsoluteContent(CommonHelper.GetImageUrl(region.ImagePath,AppConfig.MediumThumbSuffix)),
Name = region.Name,
MmName = region.MmName,
Description = region.Description,
MmDescription = region.MmDescription,
Latitude = region.Latitude,
Longitude = region.Longitude
};
regions.Add(contentRegion);
}
}
string json = JsonConvert.SerializeObject(regions);
if(!string.IsNullOrEmpty(json))
{
json = json.Trim(new char[] { '"' });
}
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ObjectContent(json.GetType(),json,Configuration.Formatters.JsonFormatter)
};
}
Actually this code should return Json array. But when I parse data from client (from Android using Volley). It cannot be parsed into Json Array.
This is the data I get:
As you can see the double quote both in the beginning and at the end. The reason I cannot parse it into array in Volley is it is returning as a string because of that double. How can I serialize it trimming that quote? I used trim, but not removed.
You are unnecessarily complicating things. In Web API you can return JSON just by returning any object inside the built-in methods, the framework will serialize it for you.
public IHttpActionResult Get()
{
IEnumerable<Region> dbRegions = regionRepo.GetCachedRegions();
List<ContentRegion> regions = new List<ContentRegion>();
if(dbRegions != null && dbRegions.Count() > 0) {
foreach(var region in dbRegions)
{
ContentRegion contentRegion = new ContentRegion
{
Id = region.Id,
ImageUrl = Url.AbsoluteContent(region.ImagePath),
SmallImageUrl = (String.IsNullOrEmpty(region.ImagePath))?null:Url.AbsoluteContent(CommonHelper.GetImageUrl(region.ImagePath,AppConfig.SmallThumbSuffix)),
MediumImageUrl = (String.IsNullOrEmpty(region.ImagePath))?null:Url.AbsoluteContent(CommonHelper.GetImageUrl(region.ImagePath,AppConfig.MediumThumbSuffix)),
Name = region.Name,
MmName = region.MmName,
Description = region.Description,
MmDescription = region.MmDescription,
Latitude = region.Latitude,
Longitude = region.Longitude
};
regions.Add(contentRegion);
}
}
return Ok(regions);
}
As an aside: from what I can see you are mapping manually your domain objects into DTOs: take into consideration the use of an automatic mapping mechanism like AutoMapper.
I am not sure this is the best solution or not. I solved the problem using this way.
This is my action method
public HttpResponseMessage Get()
{
try
{
IEnumerable<Region> dbRegions = regionRepo.GetCachedRegions();
List<ContentRegion> regions = new List<ContentRegion>();
if (dbRegions != null && dbRegions.Count() > 0)
{
foreach (var region in dbRegions)
{
ContentRegion contentRegion = new ContentRegion
{
Id = region.Id,
ImageUrl = Url.AbsoluteContent(region.ImagePath),
SmallImageUrl = (String.IsNullOrEmpty(region.ImagePath)) ? null : Url.AbsoluteContent(CommonHelper.GetImageUrl(region.ImagePath, AppConfig.SmallThumbSuffix)),
MediumImageUrl = (String.IsNullOrEmpty(region.ImagePath)) ? null : Url.AbsoluteContent(CommonHelper.GetImageUrl(region.ImagePath, AppConfig.MediumThumbSuffix)),
Name = region.Name,
MmName = region.MmName,
Description = region.Description,
MmDescription = region.MmDescription,
Latitude = region.Latitude,
Longitude = region.Longitude
};
regions.Add(contentRegion);
}
}
string json = JsonConvert.SerializeObject(regions);
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(json, Encoding.Default, "application/json")
};
}
catch
{
return Request.CreateResponse(HttpStatusCode.InternalServerError);
}
}
It's not required to convert object to json string.
You can try :
return Request.CreateResponse<List<ContentRegion>>(HttpStatusCode.OK,regions);
Not tested.
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
Use this line in your WebApiConfig.
And here your code should be
public HttpResponseMessage Get()
{
IEnumerable<Region> dbRegions = regionRepo.GetCachedRegions();
List<ContentRegion> regions = new List<ContentRegion>();
HttpResponseMessage temp = ControllerContext.Request.CreateResponse(HttpStatusCode.OK, "");
if (dbRegions != null && dbRegions.Count() > 0)
{
foreach (var region in dbRegions)
{
ContentRegion contentRegion = new ContentRegion
{
Id = region.Id,
ImageUrl = Url.AbsoluteContent(region.ImagePath),
SmallImageUrl = (String.IsNullOrEmpty(region.ImagePath)) ? null : Url.AbsoluteContent(CommonHelper.GetImageUrl(region.ImagePath, AppConfig.SmallThumbSuffix)),
MediumImageUrl = (String.IsNullOrEmpty(region.ImagePath)) ? null : Url.AbsoluteContent(CommonHelper.GetImageUrl(region.ImagePath, AppConfig.MediumThumbSuffix)),
Name = region.Name,
MmName = region.MmName,
Description = region.Description,
MmDescription = region.MmDescription,
Latitude = region.Latitude,
Longitude = region.Longitude
};
regions.Add(contentRegion);
}
}
temp = ControllerContext.Request.CreateResponse(HttpStatusCode.OK, regions);
return temp;
//string json = JsonConvert.SerializeObject(regions);
//if (!string.IsNullOrEmpty(json))
//{
// json = json.Trim(new char[] { '"' });
//}
//return new HttpResponseMessage(HttpStatusCode.OK)
//{
// Content = new ObjectContent(json.GetType(), json, Configuration.Formatters.JsonFormatter)
//};
}
I have one dropdown in the table.Once I make Onchange event I got all the table value and I want to convert it into json to send it to the servlet.
var item = [];
function dropDownOnChange(e) {
var selectedValue = e.options[e.selectedIndex].value;
alert("selectedValue:" + selectedValue);
var currentRow= $(e).closest("tr");
var AccountNo = $("td:eq(0)",$(currentRow)).text();
alert("accountno"+AccountNo);
var AccountType =$("td:eq(1)",$(currentRow)).text();
alert("acctyp"+AccountType);
var AcctypID = $("td:eq(3)",$(currentRow)).text();
alert("accID"+AcctypID);
Here I tried to convert it to JSON. I want to send this JSON value on my final save.
var objddlvalue = {};
objddlvalue["AccountNo"] = AccountNo;
objddlvalue["AccountType"] = AccountType;
objddlvalue["Account Type_Val"] = AcctypID;
objddlvalue["AccountStatus"] = selectedValue;
item.push(objddlvalue);
console.log(item);
jsonObj1 = JSON.stringify(item);
console.log(jsonObj1);
I am getting my JSON value like:
[{
"AccountNo": "89348734",
"AccountType": "Credit",
"Account Type_Val": "21",
"AccountStatus": "Invalid"
}]
When I check on online JSON checker it says the format is correct. But when I access it form servlet I can not parse it to jarray.
JSONObject jsonObj1 = (JSONObject)JSONValue.parse(request.getParameter("jsondata1"));
System.out.println("Json Object........"+jsonObj1.toJSONString());
JSONArray arr = (JSONArray) jsonObj.get(jsonObj1);
How to loop through my JSON object?
public static void main(String[] args) {
String jsonExternal = "[" +
"{"+
"\"AccountNo\": \"89348734\","+
"\"AccountType\": \"Credit\","+
"\"Account Type_Val\": \"21\","+
"\"AccountStatus\": \"Invalid\""+
"},"+
"{"+
"\"AccountNo\": \"89348734_test\","+
"\"AccountType\": \"Credit_test\","+
"\"Account Type_Val\": \"21_test\","+
"\"AccountStatus\": \"Invalid_test\""+
"}]";
JSONArray arr = (JSONArray)JSONValue.parse(jsonExternal);
for(Object obj : arr) {
JSONObject jsonObj = (JSONObject)obj;
Collection keySet = jsonObj.keySet();
Collection entrySet = jsonObj.entrySet();
Collection values = jsonObj.values();
for(Object o : keySet) {
System.out.println(o.toString());
}
for(Object o : entrySet) {
System.out.println(o.toString());
}
for(Object o : values) {
System.out.println(o.toString());
}
System.out.println(jsonObj.get("AccountNo"));
System.out.println(jsonObj.get("AccountType"));
System.out.println(jsonObj.get("Account Type_Val"));
System.out.println(jsonObj.get("AccountStatus"));
}
}