Search Results

Search found 81 results on 4 pages for 'jsonarray'.

Page 1/4 | 1 2 3 4  | Next Page >

  • API always returns JSONObject or JSONArray Best practices

    - by Michael Laffargue
    I'm making an API that will return data in JSON. I also wanted on client side to make an utility class to call this API. Something like : JSONObject sendGetRequest(Url url); JSONObject sendPostRequest(Url url, HashMap postData); However sometimes the API send back array of object [{id:1},{id:2}] I now got two choices (): Make the method test for JSONArray or JSONObject and send back an Object that I will have to cast in the caller Make a method that returns JSONObject and one for JSONArray (like sendGetRequestAndReturnAsJSONArray) Make the server always send Arrays even for one element Make the server always send Objects wrapping my Array I going for the two last methods since I think it would be a good thing to force the API to send consistent type of data. But what would be the best practice (if one exist). Always send arrays? or always send objects?

    Read the article

  • JSONArray does not work when I am getting the JSON string from the server

    - by Taehoon A Kim
    I've looked up some answers but am not sure why mine is failing exactly... The code looks something like this HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); String json = EntityUtils.toString(httpEntity); //Convert to JsonArray JSONArray jsonArray = new JSONArray(json); Log.i(DEBUG_TAG, Integer.toString(jsonArray.length())); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); Log.i(DEBUG_TAG, jsonObject.getString(KEY_ID)); // creating new HashMap HashMap<String, String> map = new HashMap<String, String>(); // adding each child node to HashMap key => value map.put(KEY_ID, jsonObject.getString(KEY_ID)); map.put(KEY_TITLE, jsonObject.getString(KEY_TITLE)); map.put(KEY_ARTIST, jsonObject.getString(KEY_ARTIST)); map.put(KEY_DURATION, jsonObject.getString(KEY_DURATION)); map.put(KEY_VOTECOUNT, jsonObject.getString(KEY_VOTECOUNT)); map.put(KEY_THUMB_URL, jsonObject.getString(KEY_THUMB_URL)); map.put(KEY_GENRE, jsonObject.getString(KEY_GENRE)); //Adding map to ArrayList if (Integer.parseInt(jsonObject.getString(KEY_VOTECOUNT)) == -1){ //If VoteCount is -1 then add to header headerList.add(map); }else { songsList.add(map); } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } When I run logcat on String json, it seems to show correct info which is kind of like this... { "userdata": [ { "id": "8", "title": "Baby One More Time", "artist": "Britney Spears", "duration": "03:24:00", "votes": "0", "thumb_url": "http://api.androidhive.info/music/images/dido.png", "genre": null }, { "id": "2", "title": "As Long As You Love Me", "artist": "Justin Bieber", "duration": "05:26:00", "votes": "0", "thumb_url": "http://api.androidhive.info/music/images/enrique.png", "genre": "Rock" } ] } and the logcat on JSONArray jsonArray = new JSONArray(json); tells me that jsonArray.length() 10-31 22:57:28.433: W/CustomizedListView(26945): error! Invalid index 0, size is 0 Please let me know Thank you,

    Read the article

  • Convert IEnumerable<dynamic> to JsonArray

    - by Burt
    I am selecting an IEnumerable<dynamic> from the database using Rob Conery's Massive framework. The structure comes back in a flat format Poco C#. I need to transform the data and output it to a Json array (format show at bottom). I thought I could do the transform using linq (my unsuccessful effort is shown below): using System.Collections.Generic; using System.Json; using System.Linq; using System.ServiceModel.Web; .... IEnumerable<dynamic> list = _repository.All("", "", 0).ToList(); JsonArray returnValue = from item in list select new JsonObject() { Name = item.Test, Data = new dyamic(){...}... }; Here is the Json I am trying to generate: [ { "id": "1", "title": "Data Title", "data": [ { "column1 name": "the value", "column2 name": "the value", "column3 name": "", "column4 name": "the value" } ] }, { "id": "2", "title": "Data Title", "data": [ { "column1 name": "the value", "column2 name": "the value", "column3 name": "the value", "column4 name": "the value" } ] } ]

    Read the article

  • Create a JSON Array using Java

    - by Ankur
    Hi I want to create a JSON array. I have tried using: JSONArray jArray = new JSONArray(); while(itr.hasNext()){ int objId = itr.next(); jArray.put(objId, odao.getObjectName(objId)); } results = jArray.toString(); Note: odao.getObjectName(objId) retrieves a name based on the "object Id" which is called objId However I get a very funny looking array like [null,null,null,"SomeValue",null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,"AnotherValue",null,null,null,null,null,null,null,null,null,null,"SomethingElse","AnotherOne","LastOne"] With only "LastOne" being displayed when I retrieve it using jQuery. The Array SHould look like {["3":"SomeValue"],["40":"AnotherValue"],["23":"SomethingElse"],["9":"AnotherOne"],["1":"LastOne"]} The numbers aren't showing up at all for some reason in the array that I am getting

    Read the article

  • Difference between following arrays?

    - by jayesh jain
    This is ARRAY1 var array_1 = ["51b59c162de88", [ ["parties", 0.0, 0.011] ]] ["51b59c1b4f52f", [ ["star-speak", 0.0, 0.006], ["parties", 0.0, 0.011] ]] This is ARRAY2 var array_2 = [{ key: "51b59c162de88", values: ["parties", 0.0, 0.011]] }, { key: "51b59c162de94", values: [ ["star-speak", 0.0, 0.006], ["parties", 0.0, 0.011] ] }, ]; What is the exact difference between array 1 and array 2. How do I access their data? I am new to json!!!!

    Read the article

  • "org.json.JSONArray implements Serializable": What's the best option to achieve this?

    - by Daxon
    I am using Grails Webflow, what ever object I pass to a view, it must be Serialized. My domain models "implement Serializable", so they work. The problem is when I get a response from a WebService. It is of the org.json.JSONArray class. I just want to pass the whole Array over to the view yet it doesn't implement Serializable, so it fails, Any thoughts on how I can pass this, or my best option? Can I just edit the source of the org.json library and make every class "imp Serializable"? Or process the result into Domain objects that do "imp Serializable"

    Read the article

  • Cant get a location

    - by user1891806
    Iam trying to get a location (latitute and longitude), I cant figure out what Im doing wrong but my location keeps returning null. Anybody knows what I am doing wrong? public class ParseJSON extends Activity implements LocationListener { private TextView latituteField; private TextView longitudeField; LocationManager lm; String provider; int lat; int lon; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.test); lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); Criteria crit = new Criteria(); provider = lm.getBestProvider(crit, false); Location location = lm.getLastKnownLocation(provider); if (location != null){ lat = (int) location.getLatitude(); lon = (int) location.getLongitude(); latituteField = (TextView) findViewById(R.id.lattest); longitudeField = (TextView) findViewById(R.id.lontest); latituteField.setText(lat); longitudeField.setText(String.valueOf(lon)); } else { Toast.makeText(ParseJSON.this, "Couldnt get location", Toast.LENGTH_SHORT); } String readWeatherFeed = readWeatherFeed(); try { JSONArray jsonArray = new JSONArray(readWeatherFeed); Log.i(ParseJSON.class.getName(), "Number of entries " + jsonArray.length()); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); Log.i(ParseJSON.class.getName(), jsonObject.getString("text")); } } catch (Exception e) { e.printStackTrace(); } } I dont have a clue, thanks in advance

    Read the article

  • Using an alternate JSON Serializer in ASP.NET Web API

    - by Rick Strahl
    The new ASP.NET Web API that Microsoft released alongside MVC 4.0 Beta last week is a great framework for building REST and AJAX APIs. I've been working with it for quite a while now and I really like the way it works and the complete set of features it provides 'in the box'. It's about time that Microsoft gets a decent API for building generic HTTP endpoints into the framework. DataContractJsonSerializer sucks As nice as Web API's overall design is one thing still sucks: The built-in JSON Serialization uses the DataContractJsonSerializer which is just too limiting for many scenarios. The biggest issues I have with it are: No support for untyped values (object, dynamic, Anonymous Types) MS AJAX style Date Formatting Ugly serialization formats for types like Dictionaries To me the most serious issue is dealing with serialization of untyped objects. I have number of applications with AJAX front ends that dynamically reformat data from business objects to fit a specific message format that certain UI components require. The most common scenario I have there are IEnumerable query results from a database with fields from the result set rearranged to fit the sometimes unconventional formats required for the UI components (like jqGrid for example). Creating custom types to fit these messages seems like overkill and projections using Linq makes this much easier to code up. Alas DataContractJsonSerializer doesn't support it. Neither does DataContractSerializer for XML output for that matter. What this means is that you can't do stuff like this in Web API out of the box:public object GetAnonymousType() { return new { name = "Rick", company = "West Wind", entered= DateTime.Now }; } Basically anything that doesn't have an explicit type DataContractJsonSerializer will not let you return. FWIW, the same is true for XmlSerializer which also doesn't work with non-typed values for serialization. The example above is obviously contrived with a hardcoded object graph, but it's not uncommon to get dynamic values returned from queries that have anonymous types for their result projections. Apparently there's a good possibility that Microsoft will ship Json.NET as part of Web API RTM release.  Scott Hanselman confirmed this as a footnote in his JSON Dates post a few days ago. I've heard several other people from Microsoft confirm that Json.NET will be included and be the default JSON serializer, but no details yet in what capacity it will show up. Let's hope it ends up as the default in the box. Meanwhile this post will show you how you can use it today with the beta and get JSON that matches what you should see in the RTM version. What about JsonValue? To be fair Web API DOES include a new JsonValue/JsonObject/JsonArray type that allow you to address some of these scenarios. JsonValue is a new type in the System.Json assembly that can be used to build up an object graph based on a dictionary. It's actually a really cool implementation of a dynamic type that allows you to create an object graph and spit it out to JSON without having to create .NET type first. JsonValue can also receive a JSON string and parse it without having to actually load it into a .NET type (which is something that's been missing in the core framework). This is really useful if you get a JSON result from an arbitrary service and you don't want to explicitly create a mapping type for the data returned. For serialization you can create an object structure on the fly and pass it back as part of an Web API action method like this:public JsonValue GetJsonValue() { dynamic json = new JsonObject(); json.name = "Rick"; json.company = "West Wind"; json.entered = DateTime.Now; dynamic address = new JsonObject(); address.street = "32 Kaiea"; address.zip = "96779"; json.address = address; dynamic phones = new JsonArray(); json.phoneNumbers = phones; dynamic phone = new JsonObject(); phone.type = "Home"; phone.number = "808 123-1233"; phones.Add(phone); phone = new JsonObject(); phone.type = "Home"; phone.number = "808 123-1233"; phones.Add(phone); //var jsonString = json.ToString(); return json; } which produces the following output (formatted here for easier reading):{ name: "rick", company: "West Wind", entered: "2012-03-08T15:33:19.673-10:00", address: { street: "32 Kaiea", zip: "96779" }, phoneNumbers: [ { type: "Home", number: "808 123-1233" }, { type: "Mobile", number: "808 123-1234" }] } If you need to build a simple JSON type on the fly these types work great. But if you have an existing type - or worse a query result/list that's already formatted JsonValue et al. become a pain to work with. As far as I can see there's no way to just throw an object instance at JsonValue and have it convert into JsonValue dictionary. It's a manual process. Using alternate Serializers in Web API So, currently the default serializer in WebAPI is DataContractJsonSeriaizer and I don't like it. You may not either, but luckily you can swap the serializer fairly easily. If you'd rather use the JavaScriptSerializer built into System.Web.Extensions or Json.NET today, it's not too difficult to create a custom MediaTypeFormatter that uses these serializers and can replace or partially replace the native serializer. Here's a MediaTypeFormatter implementation using the ASP.NET JavaScriptSerializer:using System; using System.Net.Http.Formatting; using System.Threading.Tasks; using System.Web.Script.Serialization; using System.Json; using System.IO; namespace Westwind.Web.WebApi { public class JavaScriptSerializerFormatter : MediaTypeFormatter { public JavaScriptSerializerFormatter() { SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("application/json")); } protected override bool CanWriteType(Type type) { // don't serialize JsonValue structure use default for that if (type == typeof(JsonValue) || type == typeof(JsonObject) || type== typeof(JsonArray) ) return false; return true; } protected override bool CanReadType(Type type) { if (type == typeof(IKeyValueModel)) return false; return true; } protected override System.Threading.Tasks.Taskobject OnReadFromStreamAsync(Type type, System.IO.Stream stream, System.Net.Http.Headers.HttpContentHeaders contentHeaders, FormatterContext formatterContext) { var task = Taskobject.Factory.StartNew(() = { var ser = new JavaScriptSerializer(); string json; using (var sr = new StreamReader(stream)) { json = sr.ReadToEnd(); sr.Close(); } object val = ser.Deserialize(json,type); return val; }); return task; } protected override System.Threading.Tasks.Task OnWriteToStreamAsync(Type type, object value, System.IO.Stream stream, System.Net.Http.Headers.HttpContentHeaders contentHeaders, FormatterContext formatterContext, System.Net.TransportContext transportContext) { var task = Task.Factory.StartNew( () = { var ser = new JavaScriptSerializer(); var json = ser.Serialize(value); byte[] buf = System.Text.Encoding.Default.GetBytes(json); stream.Write(buf,0,buf.Length); stream.Flush(); }); return task; } } } Formatter implementation is pretty simple: You override 4 methods to tell which types you can handle and then handle the input or output streams to create/parse the JSON data. Note that when creating output you want to take care to still allow JsonValue/JsonObject/JsonArray types to be handled by the default serializer so those objects serialize properly - if you let either JavaScriptSerializer or JSON.NET handle them they'd try to render the dictionaries which is very undesirable. If you'd rather use Json.NET here's the JSON.NET version of the formatter:// this code requires a reference to JSON.NET in your project #if true using System; using System.Net.Http.Formatting; using System.Threading.Tasks; using System.Web.Script.Serialization; using System.Json; using Newtonsoft.Json; using System.IO; using Newtonsoft.Json.Converters; namespace Westwind.Web.WebApi { public class JsonNetFormatter : MediaTypeFormatter { public JsonNetFormatter() { SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("application/json")); } protected override bool CanWriteType(Type type) { // don't serialize JsonValue structure use default for that if (type == typeof(JsonValue) || type == typeof(JsonObject) || type == typeof(JsonArray)) return false; return true; } protected override bool CanReadType(Type type) { if (type == typeof(IKeyValueModel)) return false; return true; } protected override System.Threading.Tasks.Taskobject OnReadFromStreamAsync(Type type, System.IO.Stream stream, System.Net.Http.Headers.HttpContentHeaders contentHeaders, FormatterContext formatterContext) { var task = Taskobject.Factory.StartNew(() = { var settings = new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, }; var sr = new StreamReader(stream); var jreader = new JsonTextReader(sr); var ser = new JsonSerializer(); ser.Converters.Add(new IsoDateTimeConverter()); object val = ser.Deserialize(jreader, type); return val; }); return task; } protected override System.Threading.Tasks.Task OnWriteToStreamAsync(Type type, object value, System.IO.Stream stream, System.Net.Http.Headers.HttpContentHeaders contentHeaders, FormatterContext formatterContext, System.Net.TransportContext transportContext) { var task = Task.Factory.StartNew( () = { var settings = new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, }; string json = JsonConvert.SerializeObject(value, Formatting.Indented, new JsonConverter[1] { new IsoDateTimeConverter() } ); byte[] buf = System.Text.Encoding.Default.GetBytes(json); stream.Write(buf,0,buf.Length); stream.Flush(); }); return task; } } } #endif   One advantage of the Json.NET serializer is that you can specify a few options on how things are formatted and handled. You get null value handling and you can plug in the IsoDateTimeConverter which is nice to product proper ISO dates that I would expect any Json serializer to output these days. Hooking up the Formatters Once you've created the custom formatters you need to enable them for your Web API application. To do this use the GlobalConfiguration.Configuration object and add the formatter to the Formatters collection. Here's what this looks like hooked up from Application_Start in a Web project:protected void Application_Start(object sender, EventArgs e) { // Action based routing (used for RPC calls) RouteTable.Routes.MapHttpRoute( name: "StockApi", routeTemplate: "stocks/{action}/{symbol}", defaults: new { symbol = RouteParameter.Optional, controller = "StockApi" } ); // WebApi Configuration to hook up formatters and message handlers // optional RegisterApis(GlobalConfiguration.Configuration); } public static void RegisterApis(HttpConfiguration config) { // Add JavaScriptSerializer formatter instead - add at top to make default //config.Formatters.Insert(0, new JavaScriptSerializerFormatter()); // Add Json.net formatter - add at the top so it fires first! // This leaves the old one in place so JsonValue/JsonObject/JsonArray still are handled config.Formatters.Insert(0, new JsonNetFormatter()); } One thing to remember here is the GlobalConfiguration object which is Web API's static configuration instance. I think this thing is seriously misnamed given that GlobalConfiguration could stand for anything and so is hard to discover if you don't know what you're looking for. How about WebApiConfiguration or something more descriptive? Anyway, once you know what it is you can use the Formatters collection to insert your custom formatter. Note that I insert my formatter at the top of the list so it takes precedence over the default formatter. I also am not removing the old formatter because I still want JsonValue/JsonObject/JsonArray to be handled by the default serialization mechanism. Since they process in sequence and I exclude processing for these types JsonValue et al. still get properly serialized/deserialized. Summary Currently DataContractJsonSerializer in Web API is a pain, but at least we have the ability with relatively limited effort to replace the MediaTypeFormatter and plug in our own JSON serializer. This is useful for many scenarios - if you have existing client applications that used MVC JsonResult or ASP.NET AJAX results from ASMX AJAX services you can plug in the JavaScript serializer and get exactly the same serializer you used in the past so your results will be the same and don't potentially break clients. JSON serializers do vary a bit in how they serialize some of the more complex types (like Dictionaries and dates for example) and so if you're migrating it might be helpful to ensure your client code doesn't break when you switch to ASP.NET Web API. Going forward it looks like Microsoft is planning on plugging in Json.Net into Web API and make that the default. I think that's an awesome choice since Json.net has been around forever, is fast and easy to use and provides a ton of functionality as part of this great library. I just wish Microsoft would have figured this out sooner instead of now at the last minute integrating with it especially given that Json.Net has a similar set of lower level JSON objects JsonValue/JsonObject etc. which now will end up being duplicated by the native System.Json stuff. It's not like we don't already have enough confusion regarding which JSON serializer to use (JavaScriptSerializer, DataContractJsonSerializer, JsonValue/JsonObject/JsonArray and now Json.net). For years I've been using my own JSON serializer because the built in choices are both limited. However, with an official encorsement of Json.Net I'm happily moving on to use that in my applications. Let's see and hope Microsoft gets this right before ASP.NET Web API goes gold.© Rick Strahl, West Wind Technologies, 2005-2012Posted in Web Api  AJAX  ASP.NET   Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • Android - Calling getJSONArray throwing JSONException with no stack trace

    - by Agathron
    Hi all, I'm currently working on an android app that pulls a list of forums from a JSON feed. I'm trying to parse the feed and immediately upon calling getJSONArray a JSON exception is being thrown with no stack trace. The JSON being returned is stored in an JSONObject jobj with the format as follows: { "Forum": [ {"ForumName":"CEC Employee Communications Forum","ForumId":"105"}, {"ForumName":"CEC External Stakeholder Relations Forum","ForumId":"109"}, {"ForumName":"See All...","ForumId":"0"} ] } However when running the following code, I get an immediate exception without a stack trace: JSONArray jarray = new JSONArray(); jarray = jobj.getJSONArray("Forum"); Running jobj.GetJSONArray("Forum").toString(); returns what looks to be a correct array of the format: [ {"ForumName":"CEC Employee Communications Forum","ForumId":"105"}, {"ForumName":"CEC External Stakeholder Relations Forum","ForumId":"109"}, {"ForumName":"See All...","ForumId":"0"} ] I also tried JSONArray jarray = new JSONArray(jobj.GetJSONArray("Forum").toString()); and had the exception thrown immediately. Any help would be greatly appreciated. Thanks!

    Read the article

  • How could I refactor this into more manageable methods?

    - by ChaosPandion
    private static JsonStructure Parse(string jsonText, bool throwException) { var result = default(JsonStructure); var structureStack = new Stack<JsonStructure>(); var keyStack = new Stack<string>(); var current = default(JsonStructure); var currentState = ParserState.Begin; var invalidToken = false; var key = default(string); var value = default(object); foreach (var token in Lexer.Tokenize(jsonText)) { switch (currentState) { case ParserState.Begin: switch (token.Type) { case TokenType.OpenBrace: currentState = ParserState.ObjectKey; current = result = new JsonObject(); break; case TokenType.OpenBracket: currentState = ParserState.ArrayValue; current = result = new JsonArray(); break; default: invalidToken = true; break; } break; case ParserState.ObjectKey: switch (token.Type) { case TokenType.StringLiteral: currentState = ParserState.ColonSeperator; key = (string)token.Value; break; default: invalidToken = true; break; } break; case ParserState.ColonSeperator: switch (token.Type) { case TokenType.Colon: currentState = ParserState.ObjectValue; break; default: invalidToken = true; break; } break; case ParserState.ObjectValue: case ParserState.ArrayValue: switch (token.Type) { case TokenType.NumberLiteral: case TokenType.StringLiteral: case TokenType.BooleanLiteral: case TokenType.NullLiteral: currentState = ParserState.ItemEnd; value = token.Value; break; case TokenType.OpenBrace: structureStack.Push(current); keyStack.Push(key); currentState = ParserState.ObjectKey; current = new JsonObject(); break; case TokenType.OpenBracket: structureStack.Push(current); currentState = ParserState.ArrayValue; current = new JsonArray(); break; default: invalidToken = true; break; } break; case ParserState.ItemEnd: var jsonObject = (current as JsonObject); if (jsonObject != null) { jsonObject.Add(key, value); currentState = ParserState.ObjectKey; } var jsonArray = (current as JsonArray); if (jsonArray != null) { jsonArray.Add(value); currentState = ParserState.ArrayValue; } switch (token.Type) { case TokenType.CloseBrace: case TokenType.CloseBracket: currentState = ParserState.End; break; case TokenType.Comma: break; default: invalidToken = true; break; } break; case ParserState.End: switch (token.Type) { case TokenType.CloseBrace: case TokenType.CloseBracket: case TokenType.Comma: var previous = structureStack.Pop(); var previousJsonObject = (previous as JsonObject); if (previousJsonObject != null) { currentState = ParserState.ObjectKey; previousJsonObject.Add(keyStack.Pop(), current); } var previousJsonArray = (previous as JsonArray); if (previousJsonArray != null) { currentState = ParserState.ArrayValue; previousJsonArray.Add(current); } current = previous; if (token.Type != TokenType.Comma) { currentState = ParserState.End; } break; default: invalidToken = true; break; } break; default: break; } if (invalidToken) { if (throwException) { throw new JsonException(token); } return null; } } return result; }

    Read the article

  • How could I refactor this into more manageable code?

    - by ChaosPandion
    private static JsonStructure Parse(string jsonText, bool throwException) { var result = default(JsonStructure); var structureStack = new Stack<JsonStructure>(); var keyStack = new Stack<string>(); var current = default(JsonStructure); var currentState = ParserState.Begin; var invalidToken = false; var key = default(string); var value = default(object); foreach (var token in Lexer.Tokenize(jsonText)) { switch (currentState) { case ParserState.Begin: switch (token.Type) { case TokenType.OpenBrace: currentState = ParserState.ObjectKey; current = result = new JsonObject(); break; case TokenType.OpenBracket: currentState = ParserState.ArrayValue; current = result = new JsonArray(); break; default: invalidToken = true; break; } break; case ParserState.ObjectKey: switch (token.Type) { case TokenType.StringLiteral: currentState = ParserState.ColonSeperator; key = (string)token.Value; break; default: invalidToken = true; break; } break; case ParserState.ColonSeperator: switch (token.Type) { case TokenType.Colon: currentState = ParserState.ObjectValue; break; default: invalidToken = true; break; } break; case ParserState.ObjectValue: case ParserState.ArrayValue: switch (token.Type) { case TokenType.NumberLiteral: case TokenType.StringLiteral: case TokenType.BooleanLiteral: case TokenType.NullLiteral: currentState = ParserState.ItemEnd; value = token.Value; break; case TokenType.OpenBrace: structureStack.Push(current); keyStack.Push(key); currentState = ParserState.ObjectKey; current = new JsonObject(); break; case TokenType.OpenBracket: structureStack.Push(current); currentState = ParserState.ArrayValue; current = new JsonArray(); break; default: invalidToken = true; break; } break; case ParserState.ItemEnd: var jsonObject = (current as JsonObject); if (jsonObject != null) { jsonObject.Add(key, value); currentState = ParserState.ObjectKey; } var jsonArray = (current as JsonArray); if (jsonArray != null) { jsonArray.Add(value); currentState = ParserState.ArrayValue; } switch (token.Type) { case TokenType.CloseBrace: case TokenType.CloseBracket: currentState = ParserState.End; break; case TokenType.Comma: break; default: invalidToken = true; break; } break; case ParserState.End: switch (token.Type) { case TokenType.CloseBrace: case TokenType.CloseBracket: case TokenType.Comma: var previous = structureStack.Pop(); var previousJsonObject = (previous as JsonObject); if (previousJsonObject != null) { currentState = ParserState.ObjectKey; previousJsonObject.Add(keyStack.Pop(), current); } var previousJsonArray = (previous as JsonArray); if (previousJsonArray != null) { currentState = ParserState.ArrayValue; previousJsonArray.Add(current); } current = previous; if (token.Type != TokenType.Comma) { currentState = ParserState.End; } break; default: invalidToken = true; break; } break; default: break; } if (invalidToken) { if (throwException) { throw new JsonException(token); } return null; } } return result; }

    Read the article

  • Java Cloud Service Integration to REST Service

    - by Jani Rautiainen
    Service (JCS) provides a platform to develop and deploy business applications in the cloud. In Fusion Applications Cloud deployments customers do not have the option to deploy custom applications developed with JDeveloper to ensure the integrity and supportability of the hosted application service. Instead the custom applications can be deployed to the JCS and integrated to the Fusion Application Cloud instance. This series of articles will go through the features of JCS, provide end-to-end examples on how to develop and deploy applications on JCS and how to integrate them with the Fusion Applications instance. In this article a custom application integrating with REST service will be implemented. We will use REST services provided by Taleo as an example; however the same approach will work with any REST service. In this example the data from the REST service is used to populate a dynamic table. Pre-requisites Access to Cloud instance In order to deploy the application access to a JCS instance is needed, a free trial JCS instance can be obtained from Oracle Cloud site. To register you will need a credit card even if the credit card will not be charged. To register simply click "Try it" and choose the "Java" option. The confirmation email will contain the connection details. See this video for example of the registration.Once the request is processed you will be assigned 2 service instances; Java and Database. Applications deployed to the JCS must use Oracle Database Cloud Service as their underlying database. So when JCS instance is created a database instance is associated with it using a JDBC data source.The cloud services can be monitored and managed through the web UI. For details refer to Getting Started with Oracle Cloud. JDeveloper JDeveloper contains Cloud specific features related to e.g. connection and deployment. To use these features download the JDeveloper from JDeveloper download site by clicking the "Download JDeveloper 11.1.1.7.1 for ADF deployment on Oracle Cloud" link, this version of JDeveloper will have the JCS integration features that will be used in this article. For versions that do not include the Cloud integration features the Oracle Java Cloud Service SDK or the JCS Java Console can be used for deployment. For details on installing and configuring the JDeveloper refer to the installation guideFor details on SDK refer to Using the Command-Line Interface to Monitor Oracle Java Cloud Service and Using the Command-Line Interface to Manage Oracle Java Cloud Service. Access to a local database The database associated with the JCS instance cannot be connected to with JDBC.  Since creating ADFbc business component requires a JDBC connection we will need access to a local database. 3rd party libraries This example will use some 3rd party libraries for implementing the REST service call and processing the input / output content. Other libraries may also be used, however these are tested to work. Jersey 1.x Jersey library will be used as a client to make the call to the REST service. JCS documentation for supported specifications states: Java API for RESTful Web Services (JAX-RS) 1.1 So Jersey 1.x will be used. Download the single-JAR Jersey bundle; in this example Jersey 1.18 JAR bundle is used. Json-simple Jjson-simple library will be used to process the json objects. Download the  JAR file; in this example json-simple-1.1.1.jar is used. Accessing data in Taleo Before implementing the application it is beneficial to familiarize oneself with the data in Taleo. Easiest way to do this is by using a RESTClient on your browser. Once added to the browser you can access the UI: The client can be used to call the REST services to test the URLs and data before adding them into the application. First derive the base URL for the service this can be done with: Method: GET URL: https://tbe.taleo.net/MANAGER/dispatcher/api/v1/serviceUrl/<company name> The response will contain the base URL to be used for the service calls for the company. Next obtain authentication token with: Method: POST URL: https://ch.tbe.taleo.net/CH07/ats/api/v1/login?orgCode=<company>&userName=<user name>&password=<password> The response includes an authentication token that can be used for few hours to authenticate with the service: {   "response": {     "authToken": "webapi26419680747505890557"   },   "status": {     "detail": {},     "success": true   } } To authenticate the service calls navigate to "Headers -> Custom Header": And add a new request header with: Name: Cookie Value: authToken=webapi26419680747505890557 Once authentication token is defined the tool can be used to invoke REST services; for example: Method: GET URL: https://ch.tbe.taleo.net/CH07/ats/api/v1/object/candidate/search.xml?status=16 This data will be used on the application to be created. For details on the Taleo REST services refer to the Taleo Business Edition REST API Guide. Create Application First Fusion Web Application is created and configured. Start JDeveloper and click "New Application": Application Name: JcsRestDemo Application Package Prefix: oracle.apps.jcs.test Application Template: Fusion Web Application (ADF) Configure Local Cloud Connection Follow the steps documented in the "Java Cloud Service ADF Web Application" article to configure a local database connection needed to create the ADFbc objects. Configure Libraries Add the 3rd party libraries into the class path. Create the following directory and copy the jar files into it: <JDEV_USER_HOME>/JcsRestDemo/lib  Select the "Model" project, navigate "Application -> Project Properties -> Libraries and Classpath -> Add JAR / Directory" and add the 2 3rd party libraries: Accessing Data from Taleo To access data from Taleo using the REST service the 3rd party libraries will be used. 2 Java classes are implemented, one representing the Candidate object and another for accessing the Taleo repository Candidate Candidate object is a POJO object used to represent the candidate data obtained from the Taleo repository. The data obtained will be used to populate the ADFbc object used to display the data on the UI. The candidate object contains simply the variables we obtain using the REST services and the getters / setters for them: Navigate "New -> General -> Java -> Java Class", enter "Candidate" as the name and create it in the package "oracle.apps.jcs.test.model".  Copy / paste the following as the content: import oracle.jbo.domain.Number; public class Candidate { private Number candId; private String firstName; private String lastName; public Candidate() { super(); } public Candidate(Number candId, String firstName, String lastName) { super(); this.candId = candId; this.firstName = firstName; this.lastName = lastName; } public void setCandId(Number candId) { this.candId = candId; } public Number getCandId() { return candId; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getFirstName() { return firstName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getLastName() { return lastName; } } Taleo Repository Taleo repository class will interact with the Taleo REST services. The logic will query data from Taleo and populate Candidate objects with the data. The Candidate object will then be used to populate the ADFbc object used to display data on the UI. Navigate "New -> General -> Java -> Java Class", enter "TaleoRepository" as the name and create it in the package "oracle.apps.jcs.test.model".  Copy / paste the following as the content (for details of the implementation refer to the documentation in the code): import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.core.util.MultivaluedMapImpl; import java.io.StringReader; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import oracle.jbo.domain.Number; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; /** * This class interacts with the Taleo REST services */ public class TaleoRepository { /** * Connection information needed to access the Taleo services */ String _company = null; String _userName = null; String _password = null; /** * Jersey client used to access the REST services */ Client _client = null; /** * Parser for processing the JSON objects used as * input / output for the services */ JSONParser _parser = null; /** * The base url for constructing the REST URLs. This is obtained * from Taleo with a service call */ String _baseUrl = null; /** * Authentication token obtained from Taleo using a service call. * The token can be used to authenticate on subsequent * service calls. The token will expire in 4 hours */ String _authToken = null; /** * Static url that can be used to obtain the url used to construct * service calls for a given company */ private static String _taleoUrl = "https://tbe.taleo.net/MANAGER/dispatcher/api/v1/serviceUrl/"; /** * Default constructor for the repository * Authentication details are passed as parameters and used to generate * authentication token. Note that each service call will * generate its own token. This is done to avoid dealing with the expiry * of the token. Also only 20 tokens are allowed per user simultaneously. * So instead for each call there is login / logout. * * @param company the company for which the service calls are made * @param userName the user name to authenticate with * @param password the password to authenticate with. */ public TaleoRepository(String company, String userName, String password) { super(); _company = company; _userName = userName; _password = password; _client = Client.create(); _parser = new JSONParser(); _baseUrl = getBaseUrl(); } /** * This obtains the base url for a company to be used * to construct the urls for service calls * @return base url for the service calls */ private String getBaseUrl() { String result = null; if (null != _baseUrl) { result = _baseUrl; } else { try { String company = _company; WebResource resource = _client.resource(_taleoUrl + company); ClientResponse response = resource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).get(ClientResponse.class); String entity = response.getEntity(String.class); JSONObject jsonObject = (JSONObject)_parser.parse(new StringReader(entity)); JSONObject jsonResponse = (JSONObject)jsonObject.get("response"); result = (String)jsonResponse.get("URL"); } catch (Exception ex) { ex.printStackTrace(); } } return result; } /** * Generates authentication token, that can be used to authenticate on * subsequent service calls. Note that each service call will * generate its own token. This is done to avoid dealing with the expiry * of the token. Also only 20 tokens are allowed per user simultaneously. * So instead for each call there is login / logout. * @return authentication token that can be used to authenticate on * subsequent service calls */ private String login() { String result = null; try { MultivaluedMap<String, String> formData = new MultivaluedMapImpl(); formData.add("orgCode", _company); formData.add("userName", _userName); formData.add("password", _password); WebResource resource = _client.resource(_baseUrl + "login"); ClientResponse response = resource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).post(ClientResponse.class, formData); String entity = response.getEntity(String.class); JSONObject jsonObject = (JSONObject)_parser.parse(new StringReader(entity)); JSONObject jsonResponse = (JSONObject)jsonObject.get("response"); result = (String)jsonResponse.get("authToken"); } catch (Exception ex) { throw new RuntimeException("Unable to login ", ex); } if (null == result) throw new RuntimeException("Unable to login "); return result; } /** * Releases a authentication token. Each call to login must be followed * by call to logout after the processing is done. This is required as * the tokens are limited to 20 per user and if not released the tokens * will only expire after 4 hours. * @param authToken */ private void logout(String authToken) { WebResource resource = _client.resource(_baseUrl + "logout"); resource.header("cookie", "authToken=" + authToken).post(ClientResponse.class); } /** * This method is used to obtain a list of candidates using a REST * service call. At this example the query is hard coded to query * based on status. The url constructed to access the service is: * <_baseUrl>/object/candidate/search.xml?status=16 * @return List of candidates obtained with the service call */ public List<Candidate> getCandidates() { List<Candidate> result = new ArrayList<Candidate>(); try { // First login, note that in finally block we must have logout _authToken = "authToken=" + login(); /** * Construct the URL, the resulting url will be: * <_baseUrl>/object/candidate/search.xml?status=16 */ MultivaluedMap<String, String> formData = new MultivaluedMapImpl(); formData.add("status", "16"); JSONArray searchResults = (JSONArray)getTaleoResource("object/candidate/search", "searchResults", formData); /** * Process the results, the resulting JSON object is something like * this (simplified for readability): * * { * "response": * { * "searchResults": * [ * { * "candidate": * { * "candId": 211, * "firstName": "Mary", * "lastName": "Stochi", * logic here will find the candidate object(s), obtain the desired * data from them, construct a Candidate object based on the data * and add it to the results. */ for (Object object : searchResults) { JSONObject temp = (JSONObject)object; JSONObject candidate = (JSONObject)findObject(temp, "candidate"); Long candIdTemp = (Long)candidate.get("candId"); Number candId = (null == candIdTemp ? null : new Number(candIdTemp)); String firstName = (String)candidate.get("firstName"); String lastName = (String)candidate.get("lastName"); result.add(new Candidate(candId, firstName, lastName)); } } catch (Exception ex) { ex.printStackTrace(); } finally { if (null != _authToken) logout(_authToken); } return result; } /** * Convenience method to construct url for the service call, invoke the * service and obtain a resource from the response * @param path the path for the service to be invoked. This is combined * with the base url to construct a url for the service * @param resource the key for the object in the response that will be * obtained * @param parameters any parameters used for the service call. The call * is slightly different depending whether parameters exist or not. * @return the resource from the response for the service call */ private Object getTaleoResource(String path, String resource, MultivaluedMap<String, String> parameters) { Object result = null; try { WebResource webResource = _client.resource(_baseUrl + path); ClientResponse response = null; if (null == parameters) response = webResource.header("cookie", _authToken).get(ClientResponse.class); else response = webResource.queryParams(parameters).header("cookie", _authToken).get(ClientResponse.class); String entity = response.getEntity(String.class); JSONObject jsonObject = (JSONObject)_parser.parse(new StringReader(entity)); result = findObject(jsonObject, resource); } catch (Exception ex) { ex.printStackTrace(); } return result; } /** * Convenience method to recursively find a object with an key * traversing down from a given root object. This will traverse a * JSONObject / JSONArray recursively to find a matching key, if found * the object with the key is returned. * @param root root object which contains the key searched for * @param key the key for the object to search for * @return the object matching the key */ private Object findObject(Object root, String key) { Object result = null; if (root instanceof JSONObject) { JSONObject rootJSON = (JSONObject)root; if (rootJSON.containsKey(key)) { result = rootJSON.get(key); } else { Iterator children = rootJSON.entrySet().iterator(); while (children.hasNext()) { Map.Entry entry = (Map.Entry)children.next(); Object child = entry.getValue(); if (child instanceof JSONObject || child instanceof JSONArray) { result = findObject(child, key); if (null != result) break; } } } } else if (root instanceof JSONArray) { JSONArray rootJSON = (JSONArray)root; for (Object child : rootJSON) { if (child instanceof JSONObject || child instanceof JSONArray) { result = findObject(child, key); if (null != result) break; } } } return result; } }   Creating Business Objects While JCS application can be created without a local database, the local database is required when using ADFbc objects even if database objects are not referred. For this example we will create a "Transient" view object that will be programmatically populated based the data obtained from Taleo REST services. Creating ADFbc objects Choose the "Model" project and navigate "New -> Business Tier : ADF Business Components : View Object". On the "Initialize Business Components Project" choose the local database connection created in previous step. On Step 1 enter "JcsRestDemoVO" on the "Name" and choose "Rows populated programmatically, not based on query": On step 2 create the following attributes: CandId Type: Number Updatable: Always Key Attribute: checked Name Type: String Updatable: Always On steps 3 and 4 accept defaults and click "Next".  On step 5 check the "Application Module" checkbox and enter "JcsRestDemoAM" as the name: Click "Finish" to generate the objects. Populating the VO To display the data on the UI the "transient VO" is populated programmatically based on the data obtained from the Taleo REST services. Open the "JcsRestDemoVOImpl.java". Copy / paste the following as the content (for details of the implementation refer to the documentation in the code): import java.sql.ResultSet; import java.util.List; import java.util.ListIterator; import oracle.jbo.server.ViewObjectImpl; import oracle.jbo.server.ViewRowImpl; import oracle.jbo.server.ViewRowSetImpl; // --------------------------------------------------------------------- // --- File generated by Oracle ADF Business Components Design Time. // --- Tue Feb 18 09:40:25 PST 2014 // --- Custom code may be added to this class. // --- Warning: Do not modify method signatures of generated methods. // --------------------------------------------------------------------- public class JcsRestDemoVOImpl extends ViewObjectImpl { /** * This is the default constructor (do not remove). */ public JcsRestDemoVOImpl() { } @Override public void executeQuery() { /** * For some reason we need to reset everything, otherwise * 2nd entry to the UI screen may fail with * "java.util.NoSuchElementException" in createRowFromResultSet * call to "candidates.next()". I am not sure why this is happening * as the Iterator is new and "hasNext" is true at the point * of the execution. My theory is that since the iterator object is * exactly the same the VO cache somehow reuses the iterator including * the pointer that has already exhausted the iterable elements on the * previous run. Working around the issue * here by cleaning out everything on the VO every time before query * is executed on the VO. */ getViewDef().setQuery(null); getViewDef().setSelectClause(null); setQuery(null); this.reset(); this.clearCache(); super.executeQuery(); } /** * executeQueryForCollection - overridden for custom java data source support. */ protected void executeQueryForCollection(Object qc, Object[] params, int noUserParams) { /** * Integrate with the Taleo REST services using TaleoRepository class. * A list of candidates matching a hard coded query is obtained. */ TaleoRepository repository = new TaleoRepository(<company>, <username>, <password>); List<Candidate> candidates = repository.getCandidates(); /** * Store iterator for the candidates as user data on the collection. * This will be used in createRowFromResultSet to create rows based on * the custom iterator. */ ListIterator<Candidate> candidatescIterator = candidates.listIterator(); setUserDataForCollection(qc, candidatescIterator); super.executeQueryForCollection(qc, params, noUserParams); } /** * hasNextForCollection - overridden for custom java data source support. */ protected boolean hasNextForCollection(Object qc) { boolean result = false; /** * Determines whether there are candidates for which to create a row */ ListIterator<Candidate> candidates = (ListIterator<Candidate>)getUserDataForCollection(qc); result = candidates.hasNext(); /** * If all candidates to be created indicate that processing is done */ if (!result) { setFetchCompleteForCollection(qc, true); } return result; } /** * createRowFromResultSet - overridden for custom java data source support. */ protected ViewRowImpl createRowFromResultSet(Object qc, ResultSet resultSet) { /** * Obtain the next candidate from the collection and create a row * for it. */ ListIterator<Candidate> candidates = (ListIterator<Candidate>)getUserDataForCollection(qc); ViewRowImpl row = createNewRowForCollection(qc); try { Candidate candidate = candidates.next(); row.setAttribute("CandId", candidate.getCandId()); row.setAttribute("Name", candidate.getFirstName() + " " + candidate.getLastName()); } catch (Exception e) { e.printStackTrace(); } return row; } /** * getQueryHitCount - overridden for custom java data source support. */ public long getQueryHitCount(ViewRowSetImpl viewRowSet) { /** * For this example this is not implemented rather we always return 0. */ return 0; } } Creating UI Choose the "ViewController" project and navigate "New -> Web Tier : JSF : JSF Page". On the "Create JSF Page" enter "JcsRestDemo" as name and ensure that the "Create as XML document (*.jspx)" is checked.  Open "JcsRestDemo.jspx" and navigate to "Data Controls -> JcsRestDemoAMDataControl -> JcsRestDemoVO1" and drag & drop the VO to the "<af:form> " as a "ADF Read-only Table": Accept the defaults in "Edit Table Columns". To execute the query navigate to to "Data Controls -> JcsRestDemoAMDataControl -> JcsRestDemoVO1 -> Operations -> Execute" and drag & drop the operation to the "<af:form> " as a "Button": Deploying to JCS Follow the same steps as documented in previous article"Java Cloud Service ADF Web Application". Once deployed the application can be accessed with URL: https://java-[identity domain].java.[data center].oraclecloudapps.com/JcsRestDemo-ViewController-context-root/faces/JcsRestDemo.jspx The UI displays a list of candidates obtained from the Taleo REST Services: Summary In this article we learned how to integrate with REST services using Jersey library in JCS. In future articles various other integration techniques will be covered.

    Read the article

  • Tomboy error while tring to sync with Ubuntu one; Can anyone help?

    - by Michael Chapman
    So I'm sure you've heard the song before, but after trying to sync my notes with Ubuntu One(on 10.10 AMD64) I get "Could not synchronize notes. Check the details below and try again." Of course the problem is that there are no details and trying again doesn't help. So I ran tomboy -debug and compared my error to any thing I could find about similar problems (such as the post here) but found nothing useful. Any way here's my first error, I got this using preferencessynchronizationUbuntu_one [ERROR 21:08:42.271] Synchronization failed with the following exception: String was not recognized as a valid DateTime. at System.DateTime.Parse (System.String s, IFormatProvider provider, DateTimeStyles styles) [0x00000] in <filename unknown>:0 at System.DateTime.Parse (System.String s, IFormatProvider provider) [0x00000] in <filename unknown>:0 at System.DateTime.Parse (System.String s) [0x00000] in <filename unknown>:0 at Tomboy.WebSync.Api.NoteInfo.ParseJson (Hyena.Json.JsonObject jsonObj) [0x00000] in <filename unknown>:0 at Tomboy.WebSync.Api.UserInfo.ParseJsonNoteArray (Hyena.Json.JsonArray jsonArray) [0x00000] in <filename unknown>:0 at Tomboy.WebSync.Api.UserInfo.ParseJsonNotes (System.String jsonString, System.Nullable`1& latestSyncRevision) [0x00000] in <filename unknown>:0 at Tomboy.WebSync.Api.UserInfo.GetNotes (Boolean includeContent, Int32 sinceRevision, System.Nullable`1& latestSyncRevision) [0x00000] in <filename unknown>:0 at Tomboy.WebSync.WebSyncServer.GetNoteUpdatesSince (Int32 revision) [0x00000] in <filename unknown>:0 at Tomboy.Sync.SyncManager.SynchronizationThread () [0x00000] in <filename unknown>:0 The next thing I tried was using preferencessynchronizationtomboy_web with the default 'http://one.ubuntu.com/notes/' and got the same error plus one more. [ERROR 21:12:31.949] System.ObjectDisposedException: The object was used after being disposed. at System.Net.HttpListener.CheckDisposed () [0x00000] in <filename unknown>:0 at System.Net.HttpListener.EndGetContext (IAsyncResult asyncResult) [0x00000] in <filename unknown>:0 at Tomboy.WebSync.WebSyncPreferencesWidget.<OnAuthButtonClicked>m__1 (IAsyncResult localResult) [0x00000] in <filename unknown>:0 [ERROR 21:13:19.245] Synchronization failed with the following exception: String was not recognized as a valid DateTime. at System.DateTime.Parse (System.String s, IFormatProvider provider, DateTimeStyles styles) [0x00000] in <filename unknown>:0 at System.DateTime.Parse (System.String s, IFormatProvider provider) [0x00000] in <filename unknown>:0 at System.DateTime.Parse (System.String s) [0x00000] in <filename unknown>:0 at Tomboy.WebSync.Api.NoteInfo.ParseJson (Hyena.Json.JsonObject jsonObj) [0x00000] in <filename unknown>:0 at Tomboy.WebSync.Api.UserInfo.ParseJsonNoteArray (Hyena.Json.JsonArray jsonArray) [0x00000] in <filename unknown>:0 at Tomboy.WebSync.Api.UserInfo.ParseJsonNotes (System.String jsonString, System.Nullable`1& latestSyncRevision) [0x00000] in <filename unknown>:0 at Tomboy.WebSync.Api.UserInfo.GetNotes (Boolean includeContent, Int32 sinceRevision, System.Nullable`1& latestSyncRevision) [0x00000] in <filename unknown>:0 at Tomboy.WebSync.WebSyncServer.GetNoteUpdatesSince (Int32 revision) [0x00000] in <filename unknown>:0 at Tomboy.Sync.SyncManager.SynchronizationThread () [0x00000] in <filename unknown>:0 I Have also tried removing then re-adding My computer from my Ubuntu One account, but that did not help either. The only other Thing I have noticed is that under systempreferencesubuntu one services, "Notes" is not listed as a service. I don't know if this is normal or not. Thanks for any help and please let me know if anything is confusing.

    Read the article

  • JSON Paring - How to show second Level ListView

    - by Sophie
    I am parsing JSON data into ListView, and successfully parsed first level of JSON in MainActivity.java, where i am showing list of Main Locations, like: Inner Locations Outer Locations Now i want whenever i do tap on Inner Locations then in SecondActivity it should show Delhi and NCR in a List, same goes for Outer Locations as well, in this case whenever user do tap need to show USA JSON look like: { "all": [ { "title": "Inner Locations", "maps": [ { "title": "Delhi", "markers": [ { "name": "Connaught Place", "latitude": 28.632777800000000000, "longitude": 77.219722199999980000 }, { "name": "Lajpat Nagar", "latitude": 28.565617900000000000, "longitude": 77.243389100000060000 } ] }, { "title": "NCR", "markers": [ { "name": "Gurgaon", "latitude": 28.440658300000000000, "longitude": 76.987347699999990000 }, { "name": "Noida", "latitude": 28.570000000000000000, "longitude": 77.319999999999940000 } ] } ] }, { "title": "Outer Locations", "maps": [ { "title": "United States", "markers": [ { "name": "Virgin Islands", "latitude": 18.335765000000000000, "longitude": -64.896335000000020000 }, { "name": "Vegas", "latitude": 36.114646000000000000, "longitude": -115.172816000000010000 } ] } ] } ] } Note: But whenever i do tap on any of the ListItem in first activity, not getting any list in SecondActivity, why ? MainActivity.java:- @Override protected Void doInBackground(Void... params) { // Create an array arraylist = new ArrayList<HashMap<String, String>>(); // Retrieve JSON Objects from the given URL address jsonobject = JSONfunctions .getJSONfromURL("http://10.0.2.2/locations.json"); try { // Locate the array name in JSON jsonarray = jsonobject.getJSONArray("all"); for (int i = 0; i < jsonarray.length(); i++) { HashMap<String, String> map = new HashMap<String, String>(); jsonobject = jsonarray.getJSONObject(i); // Retrieve JSON Objects map.put("title", jsonobject.getString("title")); arraylist.add(map); } } catch (JSONException e) { Log.e("Error", e.getMessage()); e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void args) { // Locate the listview in listview_main.xml listview = (ListView) findViewById(R.id.listview); // Pass the results into ListViewAdapter.java adapter = new ListViewAdapter(MainActivity.this, arraylist); // Set the adapter to the ListView listview.setAdapter(adapter); // Close the progressdialog mProgressDialog.dismiss(); listview.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Toast.makeText(MainActivity.this, String.valueOf(position), Toast.LENGTH_LONG).show(); // TODO Auto-generated method stub Intent sendtosecond = new Intent(MainActivity.this, SecondActivity.class); // Pass all data rank sendtosecond.putExtra("title", arraylist.get(position).get(MainActivity.TITLE)); Log.d("Tapped Item::", arraylist.get(position).get(MainActivity.TITLE)); startActivity(sendtosecond); } }); } } } SecondActivity.java: @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Get the view from listview_main.xml setContentView(R.layout.listview_main); Intent in = getIntent(); strReceived = in.getStringExtra("title"); Log.d("Received Data::", strReceived); // Execute DownloadJSON AsyncTask new DownloadJSON().execute(); } // DownloadJSON AsyncTask private class DownloadJSON extends AsyncTask<Void, Void, Void> { @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected Void doInBackground(Void... params) { // Create an array arraylist = new ArrayList<HashMap<String, String>>(); // Retrieve JSON Objects from the given URL address jsonobject = JSONfunctions .getJSONfromURL("http://10.0.2.2/locations.json"); try { // Locate the array name in JSON jsonarray = jsonobject.getJSONArray("maps"); for (int i = 0; i < jsonarray.length(); i++) { HashMap<String, String> map = new HashMap<String, String>(); jsonobject = jsonarray.getJSONObject(i); // Retrieve JSON Objects map.put("title", jsonobject.getString("title")); arraylist.add(map); } } catch (JSONException e) { Log.e("Error", e.getMessage()); e.printStackTrace(); } return null; }

    Read the article

  • Correct way to add objects to an ArrayList

    - by ninjasense
    I am trying to add an object to an arraylist but when I view the results of the array list, it keeps adding the same object over and over to the arraylist. I was wondering what the correct way to implement this would be. public static ArrayList<Person> parsePeople(String responseData) { ArrayList<Person> People = new ArrayList<Person>(); try { JSONArray jsonPeople = new JSONArray(responseData); if (!jsonPeople.isNull(0)) { for (int i = 0; i < jsonPeople.length(); i++) { Person.add(new Person(jsonPeople.getJSONObject(i))); } } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { } return People; } I have double checked my JSONArray data and made sure they are not duplicates. It seems to keep adding the first object over and over.

    Read the article

  • Android JSon Array is not working with Maplocations class

    - by user1505962
    I am developing a map application in android i have made maplocation class to pass latitude and longitude and using Json Array to fetch data from MYSQl to display in map.But When I run application it crashed unfortunantely here is my log cat 07-07 14:02:26.423: E/AndroidRuntime(366): FATAL EXCEPTION: main 07-07 14:02:26.423: E/AndroidRuntime(366): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.icons.draw.view/com.icons.draw.view.DrawIcons}: android.view.InflateException: Binary XML file line #6: Error inflating class com.icons.draw.view.LocationViewers 07-07 14:02:26.423: E/AndroidRuntime(366): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647) 07-07 14:02:26.423: E/AndroidRuntime(366): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663) 07-07 14:02:26.423: E/AndroidRuntime(366): at android.app.ActivityThread.access$1500(ActivityThread.java:117) 07-07 14:02:26.423: E/AndroidRuntime(366): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931) 07-07 14:02:26.423: E/AndroidRuntime(366): at android.os.Handler.dispatchMessage(Handler.java:99) 07-07 14:02:26.423: E/AndroidRuntime(366): at android.os.Looper.loop(Looper.java:130) 07-07 14:02:26.423: E/AndroidRuntime(366): at android.app.ActivityThread.main(ActivityThread.java:3683) 07-07 14:02:26.423: E/AndroidRuntime(366): at java.lang.reflect.Method.invokeNative(Native Method) 07-07 14:02:26.423: E/AndroidRuntime(366): at java.lang.reflect.Method.invoke(Method.java:507) 07-07 14:02:26.423: E/AndroidRuntime(366): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839) 07-07 14:02:26.423: E/AndroidRuntime(366): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) 07-07 14:02:26.423: E/AndroidRuntime(366): at dalvik.system.NativeStart.main(Native Method) 07-07 14:02:26.423: E/AndroidRuntime(366): Caused by: android.view.InflateException: Binary XML file line #6: Error inflating class com.icons.draw.view.LocationViewers 07-07 14:02:26.423: E/AndroidRuntime(366): at android.view.LayoutInflater.createView(LayoutInflater.java:518) 07-07 14:02:26.423: E/AndroidRuntime(366): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:570) 07-07 14:02:26.423: E/AndroidRuntime(366): at android.view.LayoutInflater.rInflate(LayoutInflater.java:623) 07-07 14:02:26.423: E/AndroidRuntime(366): at android.view.LayoutInflater.inflate(LayoutInflater.java:408) 07-07 14:02:26.423: E/AndroidRuntime(366): at android.view.LayoutInflater.inflate(LayoutInflater.java:320) 07-07 14:02:26.423: E/AndroidRuntime(366): at android.view.LayoutInflater.inflate(LayoutInflater.java:276) 07-07 14:02:26.423: E/AndroidRuntime(366): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:207) 07-07 14:02:26.423: E/AndroidRuntime(366): at android.app.Activity.setContentView(Activity.java:1657) 07-07 14:02:26.423: E/AndroidRuntime(366): at com.icons.draw.view.DrawIcons.onCreate(DrawIcons.java:16) 07-07 14:02:26.423: E/AndroidRuntime(366): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 07-07 14:02:26.423: E/AndroidRuntime(366): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611) 07-07 14:02:26.423: E/AndroidRuntime(366): ... 11 more 07-07 14:02:26.423: E/AndroidRuntime(366): Caused by: java.lang.reflect.InvocationTargetException 07-07 14:02:26.423: E/AndroidRuntime(366): at java.lang.reflect.Constructor.constructNative(Native Method) 07-07 14:02:26.423: E/AndroidRuntime(366): at java.lang.reflect.Constructor.newInstance(Constructor.java:415) 07-07 14:02:26.423: E/AndroidRuntime(366): at android.view.LayoutInflater.createView(LayoutInflater.java:505) 07-07 14:02:26.423: E/AndroidRuntime(366): ... 21 more 07-07 14:02:26.423: E/AndroidRuntime(366): Caused by: java.lang.NullPointerException 07-07 14:02:26.423: E/AndroidRuntime(366): at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:112) 07-07 14:02:26.423: E/AndroidRuntime(366): at org.json.JSONTokener.nextValue(JSONTokener.java:90) 07-07 14:02:26.423: E/AndroidRuntime(366): at org.json.JSONArray.<init>(JSONArray.java:87) 07-07 14:02:26.423: E/AndroidRuntime(366): at org.json.JSONArray.<init>(JSONArray.java:103) 07-07 14:02:26.423: E/AndroidRuntime(366): at com.icons.draw.view.LocationViewers.getMapLocations(LocationViewers.java:102) 07-07 14:02:26.423: E/AndroidRuntime(366): at com.icons.draw.view.LocationViewers.init(LocationViewers.java:65) 07-07 14:02:26.423: E/AndroidRuntime(366): at com.icons.draw.view.LocationViewers.<init>(LocationViewers.java:45) 07-07 14:02:26.423: E/AndroidRuntime(366): ... 24 more And Here is My JSOn Array and loop code to make markers double LAT; double LANG; String INFO; public List<MapLocation> getMapLocations() { if (mapLocations == null) { try{ jArray = new JSONArray(result); JSONObject json_data=null; for(int i=0;i<jArray.length();i++){ json_data = jArray.getJSONObject(i); LAT=json_data.getDouble("lat"); LANG=json_data.getDouble("lang"); INFO=json_data.getString("info"); mapLocations = new ArrayList<MapLocation>(); mapLocations.add(new MapLocation(INFO,LAT,LANG)); } } catch(JSONException e1){ Toast.makeText(getContext(), "No Vehicles Found" ,Toast.LENGTH_LONG).show(); } catch (ParseException e1) { e1.printStackTrace(); } } return mapLocations; } Please Help to Remove this error

    Read the article

  • How do I create an Array into another Array?

    - by Timnkd
    I have the following JavaScript Array: var jsonArray = { 'homes' : [ { "home_id":"203", "price":"925", "sqft":"1100", "num_of_beds":"2", "num_of_baths":"2.0", }, { "home_id":"59", "price":"1425", "sqft":"1900", "num_of_beds":"4", "num_of_baths":"2.5", }, // ... (more homes) ... ]} I want to convert this to the following type of Array (pseudo code): var newArray = new Array(); newArray.push(home_id's); How can I do that? Notice how the newArray only has home_ids from the big jsonArray array.

    Read the article

  • JavaScript: How do I create an Array into another Array?

    - by Timnkd
    I have the following JavaScript Array: var jsonArray = { 'homes' : [ { "home_id":"203", "price":"925", "sqft":"1100", "num_of_beds":"2", "num_of_baths":"2.0", }, { "home_id":"59", "price":"1425", "sqft":"1900", "num_of_beds":"4", "num_of_baths":"2.5", }, // ... (more homes) ... ]} I want to convert this in an Array like such (pseudo code): var newArray = new Array(); newArray.push(home_id's); How can I do that? Notice how the newArray only has home_ids from the big jsonArray array.

    Read the article

  • JSON parsing problem in BlackBerry

    - by anta40
    I'm working on how to parse Twitter's JSON response using JSON-ME. For example: [code] http://apiwiki.twitter.com/Twitter-Search-API-Method:-search foo({"results":[{"profile_image_url":"http://a3.twimg.com/profile_images/762620209/drama_queen-6989_normal.gif","created_at":"Thu, 01 Apr 2010 02:35:10 +0000","from_user":"TWEETSDRAMA","to_user_id":null,"text":"NEW Twitter Lists Widget - How to put it on your blog or site http://bit.ly/47NCi6","id":11401539152,"from_user_id":95081097,"geo":null,"iso_language_code":"en","source":"<a href="http://ping.fm/" rel="nofollow">Ping.fm</a>"}... (content truncated)[/code] Here's my method:[code] public void parseDataFromJSON(String strjson) throws JSONException { JSONTokener jtoken = new JSONTokener(strjson); JSONArray jsoarray = new JSONArray(jtoken); JSONObject jsobj = jsoarray.getJSONObject(0); tweeter_profile_image_url = jsobj.optString("profile_image_url"); tweeter_created_at = jsobj.optString("created_at"); tweeter_from_user = jsobj.optString("from_user"); tweeter_to_user_id = jsobj.optString("to_user_id"); tweeter_text = jsobj.optString("text"); tweeter_id = jsobj.optInt("id"); tweeter_from_user_id = jsobj.optInt("from_user_id"); tweeter_geo = jsobj.optString("geo"); tweeter_iso_language_code = jsobj.optString("iso_language_code"); tweeter_source = jsobj.optString("source") }[/code] When I ran it on the emulator, nothing was shown, so I inspected the debugger, and the output was: status: 200 content: {"results":[{"profile_image_url":"http://a1.twimg.com/profile_images/746683548/Photo_on_2010-..... --- OK, I got the JSON content org.json.me.JSONException: A JSONArray text must start with '[' at character 1 of {"results":[{"profile_image_url.... --- but somehow unable to processed it properly. So how to parse this correctly?

    Read the article

  • php json jquery and select box

    - by user253530
    I have this php code $jsonArray = array(); $sql = "SELECT ID,CLIENT FROM PLD_SERVERS"; $result = mysql_query($sql); while($row = mysql_fetch_array($result)) { $jsonArray[] = array('id'=>$row['ID'],'client'=>$row['CLIENT']); } echo json_encode($jsonArray); And this js function autosearchLoadServers() { $.post("php/autosearch-load-servers.php",function(data){ var toAppend = ""; for(var i = 0; i < data.length; i++){ toAppend += '<option value = \"' + data[i].id + '\">' + data[i].client + '</option>'; } $("#serverSelect").empty(); $("#serverSelect").html(toAppend); }); } The problem is that i get only undefined values. How can this be? The values are in the JSON, i checked using firebug in mozilla so there has to be something with the data variable but i can't understand what. I tried different ways and no results.

    Read the article

  • Drupal 7 - I can't pass post data in module function

    - by user2603290
    I can't pass post data in my custom module. filenames: mymodule.info mymodule.mod .info name = My Module description = My custom module. package = DEV version = 1.0 core = 7.x .module <?php function mymodule_menu() { $items = array(); $items['getcountries'] = array( 'title' => 'Get Countries', 'page callback' => 'getcountries', 'access arguments' => array('access content'), 'type' => MENU_CALLBACK, ); $items['getstates'] = array( 'title' => 'Get States', 'page callback' => 'getstates', 'access arguments' => array('access content'), 'type' => MENU_CALLBACK, ); return $items; } function getcountries() { $result = db_query("select distinct(country) from region"); $jsonarray = Array(); foreach ($result as $record) { $jsonarray[] = array( 'item' => $record->country, 'value' => $record->country ); } $json = json_encode($jsonarray); echo $json; } function getstates() { echo $_POST["test"]; } Ajax call $(document).ready(function(){ $.ajax({ url: '/getstates', type: 'POST', data: '{"test":"1"}', success : function () { alert('ok'); }, error : function (jqXHR, textStatus, errorThrown) { alert('error'); } }); }); The first item "getcountries" is working fine however the second one is not. I can browse to http://mysite.com/getstates ok but when I call this function using ajax it is not passing the value of "test" which is "1" to $_POST["test"]. I am new to Drupal so I am positive that I miss something here. I thought I need a new set of eyes.

    Read the article

  • pass arraylist bean from android to webservice php

    - by user1547432
    i'm newbie in android with web service i'm trying to pass arraylist from android to webservice php server here's my bean code: public class ExpressionBean { public static final String EXPRESSION_ID = "expressionID"; public static final String EXPRESSION_TEXT = "expressionText"; public static final String ANS_TEXT1 = "ansText1"; public static final String ANS_TEXT2 = "ansText2"; public static final String ASSESSEE_ANSWER = "assesseeAnswer"; private String expressionID; private String expressionText; private String ansText1; private String ansText2; private String assesseeAnswer; public String getExpressionID() { return expressionID; } public void setExpressionID(String expressionID) { this.expressionID = expressionID; } public String getExpressionText() { return expressionText; } public void setExpressionText(String expressionText) { this.expressionText = expressionText; } public String getAnsText1() { return ansText1; } public void setAnsText1(String ansText1) { this.ansText1 = ansText1; } public String getAnsText2() { return ansText2; } public void setAnsText2(String ansText2) { this.ansText2 = ansText2; } public String getAssesseeAnswer() { return assesseeAnswer; } public void setAssesseeAnswer(String assesseeAnswer) { this.assesseeAnswer = assesseeAnswer; } } and here's my doInBackround on async task : protected Boolean doInBackground(Void... params) { // TODO: attempt authentication against a network service. boolean result = false; // test = new TestBean(); // int resultTest = 0; UserFunctions userFunction = new UserFunctions(); Log.d(TAG, "UID : " + mEmail); // Log.d(TAG, "resultTest : " + resultTest); JSONObject jsonTest = userFunction.storeTest(mEmail); Log.d(TAG, "After JSON TEST "); try { if (jsonTest.getString(KEY_SUCCESS) != null) { String res = jsonTest.getString(KEY_SUCCESS); JSONObject testData = jsonTest.getJSONObject(TAG_TEST); test = new TestBean(); test.setTestid(testData.getInt(TAG_TEST_ID)); test.setUid(testData.getInt(TAG_UID)); JSONArray list = new JSONArray(); String list2; for (int position = 0; position < expressionList.size(); position++) { Gson gson = new Gson(); list.put(gson.toJson(expressionList.get(position))); } Log.d(TAG, "JSONArray list coy : " + list); UserFunctions uf = new UserFunctions(); JSONObject jsonHistoryList = new JSONObject(); jsonHistoryList = uf.storeHistoryList(list.toString()); if (Integer.parseInt(res) == 1) { result = true; finish(); } else { result = false; } } } catch (JSONException e) { e.printStackTrace(); return false; } // TODO: register the new account here. return result; } and here's storeHistoryList Method : public JSONObject storeHistoryList(String list) { // Building Parameters List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("tag", storeHistory_tag)); params.add(new BasicNameValuePair("list", list)); JSONObject json = jsonParser.getJSONFromUrl(URL, params); return json; } i want to pass list to web service list is an arraylist ExpressionBean i used gson for convert bean to json but when i execute, the log said "error parsing data... jsonarray cannot be converted to jsonobject what i must to do? thanks

    Read the article

  • How do I parse JSON from a Java HTTPResponse?

    - by Joe Ludwig
    I have an HttpResponse object for a web request I just made. The response is in the JSON format, so I need to parse it. I can do it in an absurdly complex way, but it seems like there must be a better way. Is this really the best I can do? HttpResponse response; // some response object Reader in = new BufferedReader( new InputStreamReader(response.getEntity().getContent(), "UTF-8")); StringBuilder builder= new StringBuilder(); char[] buf = new char[1000]; int l = 0; while (l >= 0) { builder.append(buf, 0, l); l = in.read(buf); } JSONTokener tokener = new JSONTokener( builder.toString() ); JSONArray finalResult = new JSONArray( tokener ); I'm on Android if that makes any difference.

    Read the article

  • Loopj Android Async Http - onFailure not fired

    - by Ashley Staggs
    I am using the great async http library from loopj, but I have run into a small snag. If the user has no internet connection or loses their connection, the app just won't return anything. This part is expected, but it also doesn't fire the onFailure method. Also, the code I have used when there is an internet connection does work so there is no problem on the server end. Here is some code that is stripped down to the minimum. It also doesn't work (I have tested this too) String url = getString(R.string.baseurl) + "/appconnect.php"; client.getHttpClient().getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true); client.get(url, null, new JsonHttpResponseHandler() { @Override public void onSuccess(JSONArray response) { Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_SHORT).show(); } @Override public void onFailure(Throwable e, JSONArray errorResponse) { Toast.makeText(getApplicationContext(), "Failure", Toast.LENGTH_SHORT).show(); } }); Thanks, Ashley

    Read the article

  • How do I correctly use generics?

    - by ninjasense
    I basically am making webrequests and recieving a JSON response. Depending on the request, I am parsing JSON request into objects I have created. The parsing is pretty much the same no matter what the object Im parsing into looks like. So I have a bunch of methods doing the same work only with different objects, I was wondering how I could accomplish this with generics? Here is an example public static ArrayList<Contact> parseContacts(String responseData) { ArrayList<Contact> Contacts = new ArrayList<Contact>(); try { JSONArray jsonContacts = new JSONArray(responseData); if (!jsonContacts.isNull(0)) { for (int i = 0; i < jsonContacts.length(); i++) { Contacts.add(new Contact(jsonContacts.getJSONObject(i))); } } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { } return Contacts; }

    Read the article

1 2 3 4  | Next Page >