vendredi 31 juillet 2015

iOnic app - use $http.delete to delete object from local JSON file

I'm trying to build my first hybrid-app, i'm trying this with iOnic but also to AngularJS. Both are totally new for me :)

But so far I'm pretty happy with the results I made because I can find a lot of stuff if I'm stuck, but now I'm lost.

I'm trying to delete a favorite object I have saved in a local JSON file by clicking the remove button that I have placed behind every favorite item.

HTML template where the favorite items are listed by ng-repeat:

<ion-view view-title="My Favorites">
<ion-content>
    <ion-list>
      <ion-item ng-repeat="favo in favos" class="row">
        <i class="col icon ion-{{favo.gender}}"></i>
        <a href="#/app/myFavos/{{favo.id}}" class="button-clear col col-80">
            {{favo.name}}
        </a>
        <a class="button button-icon icon ion-trash-b col" ng-click="removeFavo(favo.id)">
        </a>
      </ion-item>
    </ion-list>
</ion-content>

Controller.js file:

angular.module('starter.controllers', [])

.controller('FavoslistCtrl', function($scope,  myFavos) {

    myFavos.getFavos(function (data) {
        console.log(data);
        $scope.favos = data;
    });

    $scope.removeFavo = function(data) {

        myFavos.deleteFavo(favo);

    }

})

.controller('FavoCtrl', function($scope, $stateParams, myFavos) {

  $scope.favo = myFavos.getFavos($stateParams, favoId);

  myFavos.getFavo(function ($stateParams, favoId, data) {
    $scope.favo = data;
  })

});

Service.js file:

angular.module('starter.services', [])

.factory('myFavos', function($ionicLoading, $http) {


  // Might use a resource here that returns a JSON array
  return {

    getFavos: function(callback) {
      $ionicLoading.show();
      $http.get('data/favos.json').success(function (data) {
        console.log("http GET success my favorites");

        console.log("return myFavos", data);
        $ionicLoading.hide();
        return callback(data);

      }).error(function (err) {
        $scope.error = 'Could not load favorites';
      });
    },

    deleteFavo: function(favo) {
      $http.delete('data/favos/' + favos.id + '.json').success(function (data) {
        return callback(data);
      });
    },


    getFavo: function(favoId) {
      for (var i = 0; i < favos.length; i++) {
        if (favos[i].id === parseInt(favoId)) {
          return favos[i];
        }
      }
      return null;
    }
  }

});

favos.json:

[
    {
        "id":1,"name":"Adam","description": "Lorem Ipsum", "gender": "male"
    },
    {
        "id":2,"name":"Eva","description": "Lorem Ipsum", "gender": "female"
    },
    {
        "id":3,"name":"alex","description": "Lorem Ipsum", "gender": "male"
    },
    {
        "id":4,"name":"adam","description": "Lorem Ipsum", "gender": "male"
    },
    {
        "id":5,"name":"max","description": "Lorem Ipsum", "gender": "male"
    }
]

I have been trying it with the $http.delete function in the factory I made called 'myFavos' but I can't figure out how to delete the right object, with the right id.

If someone could help that would be awesome!

json_decode multidimensional from database

I have this json saved in my database in a column called 'price' with the type of 'text'.

{
  "desks": {
    "Dedicated Desk": "$400 mo"
  },
  "private offices": {
    "1 Person": "$550 mo",
    "2 Person": "$1100 mo",
    "3 Person": "$1600 mo",
    "4 Person": "$2100 mo",
    "6 Person": "$3300 mo"
  },
  "flexible membership": {
    "Starting at": "$45 mo",
    "Every Extra Day": "$50 Day"
  }
}

I then make a call from PHP to return my all the fields in my database and encode them as json.

$json = json_encode($response,JSON_PRETTY_PRINT);
echo $json;

$response is the response from the database. When I var_dump on $response I get

array(22) {
    [0]=>
      object(stdClass)#6 (38) {
        [...]

        ["price"]=>
        string(242) "{"desks":{"Dedicated Desk":"$400 mo"},"private offices":{"1 Person":"$550 mo","2 Person":"$1100 mo","3 Person":"$1600 mo","4 Person":"$2100 mo","6 Person":"$3300 mo"},"flexible membership":{"Starting at":"$45 mo","Every Extra Day":"$50 Day"}}"

        [...]
      }
    [...]
}

When I echo the result from json_encode i get

[
    {
        [...]

        "price": "{\"desks\":{\"Dedicated Desk\":\"$400 mo\"},\"private offices\":{\"1 Person\":\"$550 mo\",\"2 Person\":\"$1100 mo\",\"3 Person\":\"$1600 mo\",\"4 Person\":\"$2100 mo\",\"6 Person\":\"$3300 mo\"},\"flexible membership\":{\"Starting at\":\"$45 mo\",\"Every Extra Day\":\"$50 Day\"}}",

        [...]
    },
    [...]
]

My problem is json_encode is taking the json from the database and formatting it as a string. I am trying to get it to format it as part of a multidimensional json structure. This is what im trying to achieve:

[  
   {  
      "price":[  
         {  
            "desks":{  
               "Dedicated Desk":"$400 mo"
            },
            "private offices":{  
               "1 Person":"$550 mo",
               "2 Person":"$1100 mo",
               "3 Person":"$1600 mo",
               "4 Person":"$2100 mo",
               "6 Person":"$3300 mo"
            },
            "flexible membership":{  
               "Starting at":"$45 mo",
               "Every Extra Day":"$50 Day"
            }
         }
      ]
   }
]

Any help would be appreciated. Running latest version of php.

Unexpected behavior of Json

I am trying to create a Json, in which a question have value, option and also it contain multiple questions. and these sub questions can also contain multiple sub questions.

here is my Json string

   {
  "Questions": {
    "question": {
      "Value": " Quest 1",
      "Option": " Quest 1 Option",
      "question": {
        "Value": " Quest 2",
        "Option": " Quest 2 Option"
      },
      "question": {
        "Value": " Quest 3",
        "Option": " Quest 3 Option",
        "question": {
          "Value": " Quest 4",
          "Option": " Quest 4 Option",
          "question": {
            "Value": " Quest 5",
            "Option": " Quest 5 Option"
          },
          "question": {
            "Value": " Quest 6",
            "Option": " Quest 6 Option"
          }
        }
      }
    }
  }
}

But when I'm trying to see it in Json Viewer,ques 2 and ques 5 is missing. what I'm doing wrong here ?

Clob & JSON parsing vs dedicated table for the nodes in JSON

We are currently evaluating various data layer designs for a project.

We have JSON data (not more than few megs & less than 500 nodes all inclusive) coming in from various sources. We have finalized on 2 approaches. Also we expect not more than 500 concurrent requests.

  1. Store the JSON as CLOB in DB, and python json module to parse and extract required fields used by the web application.
  2. Design table for the JSON nodes and store it in a dedicated oracle table and retrieve for use with the web application

Need any 3rd degree view/suggestions, before our POC and performance testing.

Thanks for your help. I know the question has broader scope but I think it is specific enough to be considered here.

UPDATE:

  1. We use Oracle 11g
  2. Requirement is not for reporting but for displaying content on the Web app
  3. The web app is expected to be have 10k-30k requests /day, and we would be parsing JSON for every request. So that's 10k-30k times/day.
    1. This is just one part of the bigger web app.

What we are trying to establish is, is it worth having 500 odd columns (many tables) vs JSON parsing which can be handled with Python dicts which are faster anyway.

Convert to time in Golang from milliseconds

I have a some json data where there is a field called lastModifed contains time in millis. I wanted to convert this data into a struct type with json.UnMarshaller. I have mapped the field with json filed. But the conversion seems not working.

IE :

My Json looks like this:

{
   "name" : "hello",
   "lastModified" : 1438167001716
}

and struct Looks like

type Model struct {
    Name         string    `json:"name"`
    Lastmodified time.Time `json:"lastModified"`
}

looks not converting the time properly. how can i get the time from those millis??

NB: The millis of lastModifiedTime are getting from java System.currentTimeMillis();

converting josn data into angular js gantt chart data form

I am working on angular gantt chart and have some problem getting data from json to gantt data as they are in diffrent format

my json code is { "customers" : [ { "name" : "Doremon", "Tdate" : "2014-02-15T00:00:00", "Country" : "USA", "gender" : "M", "age" : 32, "tyear" : 2014, "ContactString" : 2 }, { "name" : "Dora", "Tdate" : "2014-02-05T00:00:00", "Country" : "FRA", "gender" : "F", "age" : 26, "tyear" : 2014, "ContactString" : 2 }, { "name" : "Popeye", "Tdate" : "2014-05-11T00:00:00", "Country" : "IND", "gender" : "M", "age" : 32, "tyear" : 2014, "ContactString" : 5 }, { "name" : "Minnie", "Tdate" : "2014-06-27T00:00:00", "Country" : "UK", "gender" : "F", "age" : 25, "tyear" : 2014, "ContactString" : 6 }, { "name" : "July", "Tdate" : "2014-09-16T00:00:00", "Country" : "PR", "gender" : "F", "age" : 25, "tyear" : 2014, "ContactString" : 9 } ] } and this should be converted into gantt chart data formatlike this example

{name: 'Status meetings', tasks: [ {name: 'Demo #1', color: '#9FC5F8', from: new Date(2013, 9, 25, 15, 0, 0), to: new Date(2013, 9, 25, 18, 30, 0)}, {name: 'Demo #2', color: '#9FC5F8', from: new Date(2013, 10, 1, 15, 0, 0), to: new Date(2013, 10, 1, 18, 0, 0)}, {name: 'Demo #3', color: '#9FC5F8', from: new Date(2013, 10, 8, 15, 0, 0), to: new Date(2013, 10, 8, 18, 0, 0)}, {name: 'Demo #4', color: '#9FC5F8', from: new Date(2013, 10, 15, 15, 0, 0), to: new Date(2013, 10, 15, 18, 0, 0)}, {name: 'Demo #5', color: '#9FC5F8', from: new Date(2013, 10, 24, 9, 0, 0), to: new Date(2013, 10, 24, 10, 0, 0)} ]},

so please if someone could tell some software or some technique for this conversion it would be very helpful

How do you create a responsive tabular feed that displays the result of an API in a tab?

I have a URL that returns JSON data. I want to create a table that displays the results from each API in a responsive tabbed panel and I am not sure how to start.

Here is a sample API URL http://ift.tt/1IAdlX0

Newbie coder here teaching myself to code.

Add a texture in ressource pack to a json model

I am using Windows 7 and BDCraft Cubik PRO.

In Minecraft 1.8, we can set a model to an item. I export my work to a .json file and all the textures I applied on it can't be found.

I don't know where or how can I put these textures on this .json file.

Inserting JSON subdocuments into Informix tables

I've set up an Informix 12.10 Innovater-C (free version) database. I've connected a Meteor/Mongo app remotely to it using the Informix mongo wire listener.

I've created a table with the following structure:

hashtags MULTISET(VARCHAR(255) not NULL),
fullcomment VARCHAR(255),
url ROW(hostname VARCHAR(255), link VARCHAR(100))

I can insert rows using sql (e.g. using dbaccess), and they show up in meteor perfectly, with the hashtags being an array of strings, and url being an object. An example object returned would be:

{   hashtags: [ 'xyz', 'abc' ],
    fullcomment: 'this is comment',
    url: { hostname: 'www.google.com', link: 'link' }
} 

However, in Meteor, I can't insert rows using the usual collection.insert() syntax. As long as I'm inserting a field containing only simple datatypes (i.e. no sets and no rows) then it works. For example, in the above defined table, I can do collection.insert({fullcomment: "comment"}) which will work and leave the other fields null.

When I try to insert a document with a url object with the following statement:

clips.insert({
   fullcomment: "this is comment",
   url: {hostname: "www.google.com", link: "xyz"}
});

I get the following error:

MongoError: Unable to insert into table testclip3: -9634 No cast from bson to ROW(hostname varchar(255), link varchar(100)). | No cast from bson to ROW(hostname varchar(255), link varchar(100)). (SQL Code: -9634, SQL State: IX000)

Similarly, if I try to insert a hashtags field containing an array, I get:

MongoError: Unable to insert into table testclip2: -9634 No cast from bson to MULTISET(char(255) not null). | No cast from bson to MULTISET(char(255) not null). (SQL Code: -9634, SQL State: IX000)

Am I doing something wrong with my table setups? Or is there a way I can specify the appropriate cast on the server side? I'm trying to keep the Meteor/Mongo side untouched if possible so I can transition an application over from Mongo to Informix.

The alternatives I see would be:

  1. Use a BSON column in Informix to store the JSON documents natively. This works, but I'd really like to use native columns so that I can set up parent/child relationships, etc. like normal relational tables. This is mitigated by the fact that Informix allows you to construct views from JSON fields, but it seems that it'd be easier to try to keep a normal table structure as much as possible
  2. Use SQL on the Meteor side to insert documents. This would be a real pain, as it would involve manually unwinding and translating objects into the appropriate fields, which I'm hoping to avoid.

Anyway, thanks for any insights or suggestions you might have.

loading json data from local file into React JS

I have a React component and I want to load in my JSON data from a file. The console log currently doesn't work, even though I'm creating the variable data as a global

'use strict';

var React = require('react/addons');

// load in JSON data from file
var data;

var oReq = new XMLHttpRequest();
oReq.onload = reqListener;
oReq.open("get", "data.json", true);
oReq.send();

function reqListener(e) {
    data = JSON.parse(this.responseText);
}
console.log(data);

// create component
var Accordion = React.createClass({      
  render: function(){
    return (
      <div>
          Accordion component          
      </div>
    );
  }
});

module.exports = Accordion;

Ideally, I would prefer to do it something like this, but it's not working - it tries to add ".js" onto the end of the filename.

var data = require('./data.json');

Any advice on the best way, preferably the "React" way, would be much appreciated!

ajax post data undefined

I'm using xampp-control to emulate a local server. I have a html file and i'm trying with ajax to post some data into a json file. I can get the data from the json, but when I'm trying to post doesn't work.

here is the html

<!doctype html>
<html class="no-js" lang="">
    <head>
        <script src="http://ift.tt/1LdO4RA"></script>
        <script src="js/main.js"></script>
    </head>

    <body>
        <h1> Family Perez</h1>
        <form>
            <label>Name</label><input type="input" id="name" name="name"></input>
            <label>Last Name</label><input type="input" id="lastName" name="lastName"></input>
            <input type="submit" id="submitBtn" value="Add family Member" name="submit"></input>

        </form>

        <div></div>
    </body>
</html>

and here is the js

$(function(){

  $('#submitBtn').click(function(e){
    e.preventDefault();
    var firtsName = $('#name').val();
    var lastName = $('#lastName').val();

    $.ajax({
      type: 'post',
      url:'http://localhost/angel/Jquery_advanced/ajax/family.json',
      dataType: 'json',
      async: false,
      data: {name: firtsName, last: lastName},
      success: function(newMember){
          alert(newMember.name + ' ' + newMember.last + ' ' + 'has benn added');
      },
      error: function (jqXHR, textStatus, errorThrown){
        console.log(jqXHR);
        console.log(textStatus);
        console.log(textStatus);
      }
    })

  });

  $.ajax({
    type: 'GET',
    dataType: 'json',
    url: 'http://localhost/angel/Jquery_advanced/ajax/family.json',
    success: function(data) {
      $.each(data, function(i, member){
        $('div').append('<p>'+ member.name + ' ' + member.last +'</p>');
      })
    }
  });
});

the file http://localhost/angel/Jquery_advanced/ajax/family.json has:

[{"name":"Juliseth","last":"Hernandez"},{"name":"Angel","last":"Perez"}]

How to Append multiple objects in to Nested JSON?

Aim:- To create Restaurant Business Hours for all days.

Steps I followed :-

1). Used Post method from service ($http.Post)

2). Binded UI Elements with ng-model. (

3). Used Post Method for every Tab

Output :- Seven Different Objects instead of Nested Json Object .

Could Any one Guys Give me some Ideas Or Sample Code for appending all the small Jsons in to Nested Json Like Following .

Plunker http://ift.tt/1IA9Zn1

Outputs:-

Actual Ouput Needed.

{
 displayName:"My Restaurnat BusinessHours"
    sun:{
         Opened:true,
         open:"10:00 Am",
         close:"10:00 PM"
          },
    mon:{
         Opened:true,
         open:"10:00 Am",
         close:"10:00 PM"
          },
    tue:{
         Opened:true,
         open:"10:00 Am",
         close:"10:00 PM"
          }

    }

Wrong Out Put :-

{
    displayName:"My Restaurnat BusinessHours"
sun:{
     Opened:true,
     open:"10:00 Am",
     close:"10:00 PM"
      } 
 }


 {
    displayName:"My Restaurnat BusinessHours"
mon:{
     Opened:true,
     open:"10:00 Am",
     close:"10:00 PM"
      } 
 }

 {
    displayName:"My Restaurnat BusinessHours"
tue:{
     Opened:true,
     open:"10:00 Am",
     close:"10:00 PM"
      } 
 }

JSON return value to global variable

Simply my code looks like this:

 var thevariable = 0;

For(){
//somecode using thevariable
$.getJSON('',{},function(e){
//success and i want to set the returned value from php to my variable to use it in the forloop

thevariable = e.result;
});
}

my main problem that the variable value stays "0", during the whole For loop, while i only want it to be "0" at the first loop, then it takes the result returned from PHP to use it on for loop.

here it my real code if you need to take a look:

var orderinvoice = 0;
for(var i=0; i<table.rows.length; i++){
                            var ordername = table.rows[i].cells[5].innerText;
                            var orderqty = ((table.rows[i].cells[1].innerText).replace(/\,/g,'')).replace(/Qty /g,'');
                            var orderprice = (table.rows[i].cells[2].innerText).replace(/\$/g,'');
                            var ordertype = table.rows[i].cells[3].innerText;
                            var orderlink = table.rows[i].cells[4].innerText;

      $.getJSON('orderprocess.php', {'invoice': orderinvoice, 'pay_email': email, 'ord_name': ordername, 'ord_qty': orderqty, 'ord_price': orderprice, 'ord_type': ordertype, 'ord_link': orderlink}, function(e) {
          console.log();
          document.getElementById("result").innerText= document.getElementById("result").innerText + "Order #"+e.result+" Created Successfully ";
         document.getElementById("invoker").innerText = ""+e.invoice;
         orderinvoice = e.invoice;

          if(i+1 == table.rows.length){
            document.getElementById("result").innerText= document.getElementById("result").innerText + "With invoice #" + e.invoice;
          }
 });

Logstash: Parse Complicated Multiline JSON from log file into ElasticSearch

Let me first say that I have gone through as many examples on here as I could that still do not work. I am not sure if it's because of the complicated nature of the JSON in the log file or not.

I am looking to take the example log entry, have Logstash read it in, and send the JSON as JSON to ElasticSearch.

Here is what the (shortened) example looks:

[0m[0m16:02:08,685 INFO  [org.jboss.as.server] (ServerService Thread Pool -- 28) JBAS018559: {
"appName": "SomeApp",
"freeMemReqStartBytes": 544577648,
"freeMemReqEndBytes": 513355408,
"totalMem": 839385088,
"maxMem": 1864368128,
"anonymousUser": false,
"sessionId": "zz90g0dFQkACVao4ZZL34uAb",
"swAction": {
    "clock": 0,
    "clockStart": 1437766438950,
    "name": "General",
    "trackingMemory": false,
    "trackingMemoryGcFirst": true,
    "memLast": 0,
    "memOrig": 0
},
"remoteHost": "127.0.0.1",
"remoteAddr": "127.0.0.1",
"requestMethod": "GET",
"mapLocalObjectCount": {
    "FinanceEmployee": {
      "x": 1,
      "singleton": false
    },
    "QuoteProcessPolicyRef": {
      "x": 10,
      "singleton": false
    },
    "LocationRef": {
      "x": 2,
      "singleton": false
    }
},
"theSqlStats": {
    "lstStat": [
      {
        "sql": "select * FROM DUAL",
        "truncated": false,
        "truncatedSize": -1,
        "recordCount": 1,
        "foundInCache": false,
        "putInCache": false,
        "isUpdate": false,
        "sqlFrom": "DUAL",
        "usingPreparedStatement": true,
        "isLoad": false,
        "sw": {
          "clock": 104,
          "clockStart": 1437766438970,
          "name": "General",
          "trackingMemory": false,
          "trackingMemoryGcFirst": true,
          "memLast": 0,
          "memOrig": 0
        },
        "count": 0
      },
      {
        "sql": "select * FROM DUAL2",
        "truncated": false,
        "truncatedSize": -1,
        "recordCount": 0,
        "foundInCache": false,
        "putInCache": false,
        "isUpdate": false,
        "sqlFrom": "DUAL2",
        "usingPreparedStatement": true,
        "isLoad": false,
        "sw": {
          "clock": 93,
          "clockStart": 1437766439111,
          "name": "General",
          "trackingMemory": false,
          "trackingMemoryGcFirst": true,
          "memLast": 0,
          "memOrig": 0
        },
        "count": 0
      }
    ]
    }
}

The Logstash configs I have tried have not worked. The one closest so far is:

input {
    file {
        codec => multiline {
            pattern => '\{(.*)\}'
            negate => true
            what => previous
        }
        path => [ '/var/log/logstash.log' ]
        start_position => "beginning"
        sincedb_path => "/dev/null"
    }
}

filter {
    json {
        source => message
    }
}

output {
    stdout { codec => rubydebug }
    elasticsearch {
        cluster => "logstash"
        index => "logstashjson"
    }
}

I have also tried:

input {
    file {
        type => "json"
        path => "/var/log/logstash.log"
        codec => json #also tried json_lines
    }
}

filter {
    json {
        source => "message"
    }
}

output {
    stdout { codec => rubydebug }
    elasticsearch {
        cluster => "logstash"
        codec => "json" #also tried json_lines
        index => "logstashjson"
    }
}

I just want to take the JSON posted above and send it "as is" to ElasticSearch just as if I did a cURL PUT with that file. I appreciate any help, thank you!

UPDATE

After help from Leonid, here is the configuration I have right now:

input {
    file {
        codec => multiline {
            pattern => "^\["
            negate => true
            what => previous
        }
        path => [ '/var/log/logstash.log' ]
        start_position => "beginning"
        sincedb_path => "/dev/null"
    }
}

filter {
    grok {
        match => { "message" => "^(?<rubbish>.*?)(?<logged_json>{.*)" }
    }
    json {
        source => "logged_json"
        target => "parsed_json"
    }
}

output {
    stdout {
        codec => rubydebug
    }
    elasticsearch {
        cluster => "logstash"
        index => "logstashjson"
    }
}

Unexpected Identifier in Javascript for speech

I'm making a Visual Novel and I've come across an error in the code for the speech from the main character. Here is the code which I've tried using.

chapter1 = {
    label, "chapter1"
    text, {
        value: "Ughhhh",
        speaker: "Me",
        append: false,
        align: "left"
    },
];

Can I ask what I'm doing wrong or what I'm missing? And also, I've checked it out and it says that the unexpected identifier is the text, { part of the code

Looking for something in json file then trying something else if it doesnt work

Im getting json files from a site and i want it to find which ever one gets the file and use that one. Im using the $_GET Method too. There are 2 ways of getting the same file but they both require an id or a custom url from steam.

My url example: http://ift.tt/1DgKUNc

2 ways of getting json file:

How im decoding it:

$id = $_GET['id'];
$url = "http://ift.tt/GFGALB".$id."/inventory/json/730/2";
$content = file_get_contents($url);
$playerinfo = json_decode($content, true);
$InventoryStatus = $playerinfo['success'];

Active class on links angular js with ng-click?

I have a menu with links that are loaded from a json file. I am wondering what is the best way to add an active class when the user clicks the link. I have seen examples with unordered lists, but none with actual links. I have tried it with ng-click on the anchor tag, but it doesnt work. Here is the code that I have so far. What do you suggest is the best way to implement this?

Menu.html

<ul ng-controller="menuList">
   <li ng-repeat="words in allTerms track by $index"  ng-class="{ 'active': $index == selectedIndex}"><a href  id="{{ $index }}" ng-click="testing($event); PracticeTerm(); itemClicked($index);">{{words.term}}</a></li>
</ul>

controller.js

$scope.selectedIndex = 0;

$scope.itemClicked = function($index) {
    console.log($index);
    $scope.selectedIndex = $scope.allTerms[$scope.shared[$scope.shared.length - 1]].term;
};

Best practices for updating local JSON data file in Swift app?

My app will ship with a local JSON file for the data, so that everything functions properly offline (because the region the app is based on is hit or miss on connections). I would like to be able to update the local file from time to time with an updated version that is hosted on a server.

Should I download the updated file and overwrite the local file with it, or is there a way to check to see if the file has been updated before downloading?

Also, what event would be best to do these type of tasks on? Downloading the file and overwriting the local copy every time the app runs seems like overkill, but I don't really know how I would go about checking the server file to see if the file is newer before downloading.

I'm new to programming in general, so I don't really know the best practices way to handle something like this.

Any help is appreciated.

Is there a way to default all properties as required in json-schema?

I am making a fairly large json-schema (draft 4) and want all properties to be required, without having to add each property to the required array. Is it possible to set all properties as required by default?

How can I get a Spring @RestController to accept parameters in JSON format rather than www-form-urlencoded?

Using Spring 4.1.7 on JDK 1.8, I have an @RestController class that looks like this:

@RestController
public class ServiceAController {

    public static final Logger LOG = Logger.getLogger(ServiceAController.class);

    @RequestMapping(value="/rest/servicea", method=RequestMethod.POST)
    public ServiceAResponse serviceA(@RequestParam(value="parmA", defaultValue="defaultParmA") String parmA,
            @RequestParam(value="parmB", defaultValue="defaultParmB") String parmB,
            @RequestParam(value="parmC", defaultValue="defaulParmC") String parmC) {
        LOG.info("Inside Service A handler: " + parmA + " B: "+ parmB + " C: "+ parmC);
}

When I send a POST to /rest/servicea from a javascript like this, everything works, and I see the values "a", "b", and "c" printed in my log:

    var data = {        
        "parmA": "a",
        "parmB": "b",
        "parmC": "c"
    }

    $.ajax({
        type: "POST",
        url: "./rest/servicea",
        contentType: "application/x-www-form-urlencoded",
        data: data,
        dataType: "json",
        success: submitAuthSuccess,
        error: submitAuthFailure 
    })

However, when I try to change the call from the javascript to this (to change the protocol to REST rather than www-urlencode), I get the default values (defaultParmA, defaultParmB, defaultParmC) in my log:

    var data = {        
        "parmA": "a",
        "parmB": "b",
        "parmC": "c"
    }

    $.ajax({
        type: "POST",
        url: "./rest/servicea",
        contentType: "application/json",
        data: JSON.stringify(data),
        dataType: "json",
        success: submitAuthSuccess,
        error: submitAuthFailure 
    })

I think I'm missing something in the @RestController class to get it to parse the JSON rather than expecting www-urlencoded data.

What can I change to make this work, using JSON rather than urlencoded data in the POST body?

MongoDB how do I get the schema from schemaless?

I am recieving a JSON object into mongodb

$instagram->setAccessToken($_SESSION['InstagramAccessToken']);
$popular = $instagram->getPopularMedia();
var_dump($popular);
$conn = new MongoClient('mongodb://localhost/?w=1');
$db = $conn->instagram;
$collection = $db->instagram1;
$collection->insert($popular);

No errors and I can see the data in the collection

But when I google how to see the layout, the samples given don't seem to work for me.

var myvar = db.instagram1.findOne();
for (var key in myvar){print (key);}
_id
foo
bar

mongo session output

I am a mongo n00b (mysql defector)

var_dump() output (raw object data)

how do I get a printout of the column headings and attributes associated with my imported JSON data? (the schema for the schemaless?)

How to i add a custom style_formats with using data from the database on tinymce? (For ASP.NET MVC)

I use TinyMCE editor. And i want to create a custom inline styles for a span tag. But style datas should come from the database. In this way the data can be obtained.

    $(document).ready(function () {

        $.ajax({
            type: "POST",
            url: '@Url.Action("GetFormats", "Editor")',
            dataType: "json",
            success: function (formats) {
                $.each(formats, function (index, format) {
                    // Datas from database
                });
            }
        });
    });

and define tinymce

    tinymce.init({           
    selector: "textarea",
        theme: "modern",
        plugins: [
            "advlist autolink lists link image charmap print preview hr anchor pagebreak",
            "searchreplace wordcount visualblocks visualchars code fullscreen",
            "insertdatetime media nonbreaking save table contextmenu directionality",
            "emoticons template paste textcolor colorpicker textpattern imagetools"
        ],
        toolbar1: "insertfile undo redo | styleselect formatselect fontselect fontsizeselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image media",
        toolbar2: "cut copy paste | searchreplace | print preview removeformat | forecolor backcolor emoticons",

        image_advtab: true,

        style_formats: [
        {
            title: 'My_Style_Combo', inline: 'span', styles: { color: 'rgb(0, 0, 255)', fontFamily: 'comic sans ms,cursive', fontSize:'12px',textDecoration:'underline' } 
        }
       //------> How can I integrate my each data here like this format type?
        ]

    });

I'm sorry for my bad English if you have difficulty in understanding.

I hope it has been a true expression. Thank you in advance for your answers.

JsonRPCClient Not working some times

I'm trying to use Blockchain.info's JsonRPC API,

Code:

require_once 'jsonRPCClient.php';

$user = "************************************";
$pass = "***********";
$host = "rpc.blockchain.info";
$port = 443;

$url = "https://{$user}:{$pass}@{$host}:{$port}";
$rpc = new jsonRPCClient("{$url}");

It works with some methods such as getblockcount, like this:

$do = $rpc->getblockcount();
echo var_dump($do);

But it doesn't work on many methods such as getinfo:

$do = $rpc->getinfo();
echo var_dump($do);

(I get error: Undefined index: id jsonRPCClient.php on line 151)

What am I doing wrong here?

Am I missing something?

How to get and load nested JSON values into Tableview Objective c?

Below I have posted my nested JSON response. I want to get all the keys and key values to load into one tableview like below UI. Please help me!

My JSON

response : {

     ANI =  { 
             name = "anisharmu";
             age  = "10";
     };

     ROC =  { 
             name = "rockins";
             age  = "20";   
     };
}

MY UI Tableview

|------------------------|
  ANI anisharmu - 10
|------------------------|

My Code

 NSError *error;
 jsonDictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
 // get keys from response dictionary
 NSMutableArray * key = [[NSMutableArray alloc] initWithArray:[jsonDictionary[@"response"] allKeys]];

 // sort as asending order
 NSSortDescriptor* sortOrder = [NSSortDescriptor sortDescriptorWithKey: @"self" ascending: YES];
 key =  (NSMutableArray *)[key sortedArrayUsingDescriptors: [NSArray arrayWithObject: sortOrder]];

 // access inner data from dictonary
 for (NSString * obj in key) {

            NSLog(@"%@",jsonDictionary[@"response"][obj][@"name"]);

 }

How can I filter through json data by using the input checbox and showing or hiding products that meet the criteria

I have data stored in an array and when I click on a checkbox I would like to show the item that meet the criteria and hide the ones that don't. For example if I have a list of products that are being rendered through a for loop and when I click the check box for android I would like to only show android phones. Heres my code so far.

var data = {"products": [

{
    "Name": "Apple iPhone6 16GB",
    "OS": "iOS",
    "Camera": "16mp",
    "Price": "$" + 99.99,
    "Specs": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce vel finibus ligula. Duis pretium, velit eget venenatis laoreet, eros nulla facilisis eros, quis consectetur nisl sapien ut justo. Nulla et erat ex. Morbi tincidunt vitae tellus eget iaculis. Sed imperdiet, justo et ultricies imperdiet, leo ante elementum nunc, et facilisis mauris felis id felis. Etiam sit amet dolor purus. Vestibulum et hendrerit neque, sit amet gravida dolor."

},

{
    "Name": "Samsung- Galaxy S6 32GB",
    "OS": "android",
    "Camera": "16mp",
    "Price": "$" + 199.99,
    "Specs": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce vel finibus ligula. Duis pretium, velit eget venenatis laoreet, eros nulla facilisis eros, quis consectetur nisl sapien ut justo. Nulla et erat ex. Morbi tincidunt vitae tellus eget iaculis. Sed imperdiet, justo et ultricies imperdiet, leo ante elementum nunc, et facilisis mauris felis id felis. Etiam sit amet dolor purus. Vestibulum et hendrerit neque, sit amet gravida dolor."

},
{
    "Name": "HTC One M9 32GB",
    "OS": "android",
    "Camera": "16mp",
    "Price": "$" + 199.99,
    "Specs": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce vel finibus ligula. Duis pretium, velit eget venenatis laoreet, eros nulla facilisis eros, quis consectetur nisl sapien ut justo. Nulla et erat ex. Morbi tincidunt vitae tellus eget iaculis. Sed imperdiet, justo et ultricies imperdiet, leo ante elementum nunc, et facilisis mauris felis id felis. Etiam sit amet dolor purus. Vestibulum et hendrerit neque, sit amet gravida dolor."

},
{
    "Name": "Apple iPhone6 Plus 32GB",
    "OS": "iOS",
    "Camera": "16mp",
    "Price": "$" + 399.99,
    "Specs": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce vel finibus ligula. Duis pretium, velit eget venenatis laoreet, eros nulla facilisis eros, quis consectetur nisl sapien ut justo. Nulla et erat ex. Morbi tincidunt vitae tellus eget iaculis. Sed imperdiet, justo et ultricies imperdiet, leo ante elementum nunc, et facilisis mauris felis id felis. Etiam sit amet dolor purus. Vestibulum et hendrerit neque, sit amet gravida dolor."

},
{
    "Name": "Samsung Galaxy Note 5 32GB",
    "OS": "android",
    "Camera": "16mp",
    "Price": "$" + 499.99,
    "Specs": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce vel finibus ligula. Duis pretium, velit eget venenatis laoreet, eros nulla facilisis eros, quis consectetur nisl sapien ut justo. Nulla et erat ex. Morbi tincidunt vitae tellus eget iaculis. Sed imperdiet, justo et ultricies imperdiet, leo ante elementum nunc, et facilisis mauris felis id felis. Etiam sit amet dolor purus. Vestibulum et hendrerit neque, sit amet gravida dolor."

},
{
    "Name": "LG G Flex 2 32GB",
    "OS": "android",
    "Camera": "16mp",
    "Price": "$" + 199.99,
    "Specs": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce vel finibus ligula. Duis pretium, velit eget venenatis laoreet, eros nulla facilisis eros, quis consectetur nisl sapien ut justo. Nulla et erat ex. Morbi tincidunt vitae tellus eget iaculis. Sed imperdiet, justo et ultricies imperdiet, leo ante elementum nunc, et facilisis mauris felis id felis. Etiam sit amet dolor purus. Vestibulum et hendrerit neque, sit amet gravida dolor."

}

]}

for(var i =0; i < data.products.length; i++){ $('#productList').append('' + '

' + data.products[i].Name + '

' + '' + data.products[i].OS + '' + '' + data.products[i].Camera + '' + '' + data.products[i].Price + '' + '

' + data.products[i].Specs);

}

Here's my html

   <div id="container">

       <ul id="mainNav">
           <li>Device Manufacturer
               <ul>
                   <li><input type="checkbox" name= "device" value="Apple"> Apple</li>
                   <li><input type="checkbox" name= "device" value="HTC"> HTC</li>
                   <li><input type="checkbox" name= "device" value="LG"> LG</li>
                   <li><input type="checkbox" name= "device" value="Samsung"> Samsung</li>
               </ul>

           </li>
           <li>Operating System
               <ul>
                   <li><input type="checkbox" name= "device" value="Android"> Android</li>
                   <li><input type="checkbox" name= "device" value="ios"> iOS</li>

               </ul>

           </li>
           <li>Camera
               <ul>
                   <li><input type="checkbox" name= "device" value="8mp"> 8mp</li>
                   <li><input type="checkbox" name= "device" value="16mp"> 16mp</li>

               </ul>

           </li>
           <li>Storage
                <ul>
                   <li><input type="checkbox" name= "device" value="Apple"> 16GB</li>
                   <li><input type="checkbox" name= "device" value="Apple"> 32GB</li>
                   <li><input type="checkbox" name= "device" value="Apple"> 64GB</li>

               </ul>


           </li>
       </ul>

        <div id="productList"></div>


    </div>

php request authorization from remote server

I have two servers, server 1 (the host) is provide content to server 2 (the client).

On server 2 I am using

file_get_contents('http://ift.tt/1MCsR7t');

to retrieve the requested file content. But before this content can be retrieved on server 2 I would like to implement some sort of authentication (username/password). I was thinking about including a username and password query in the url for fgc and checking the db on server 1 before the content is sent back but there will be some cases where the fgc content will need to be printed multiple times through a loop so if the fgc is called say 10 times I don't want to hit the db on server 1 10 times.

So basically I would like to be able to make one call to an auth file on server one or something similar that will give access to the content fetched by the fgc. Maybe with JSON or something? But I've never used JSON with php so I'm not sure how that would work.

Any help would be greatly appreciated. Thanks in advance.

ArangoDB search by string field

I want to do a simple search by text in a specific field of a specific collection in ArangonDB. Something like this ( in SQL ):

SELECT * FROM procedures WHERE procedures.name LIKE '%hemogram%'

I need to search in a string field of object ( document? ) that is part of an array that is a field of my actuall document:

[
  {
    "name": "Unimed",
    "procedures": [
      {
        "type": "Exames",
        "name": "Endoscopia"
      },
      {
        "type": "Exame",
        "name": "Hemograma"
      }
    ]
  }
]

I want to retrieve, for example, all procedures that name likes a "string", searching in all documents of my clinics collection.

I've been reading about fulltext indexes but I couldn't understand how to create or how to use them.

Any help would be great!

EDIT

I almost got what I wanted. My problem is now return just the information I want.

FOR clinic IN clinics
  FILTER LIKE(clinic.procedures[*].name, '%hemogram%', true)
  RETURN{
   clinic_name: clinic.name,
   procedure: clinic.procedures
  }

This returns to me all the procedures in a given clinic ( procedures is an array inside a clinic ) and not only the procedure which the field name is 'LIKE' my search string. How can I achieve this?

how to parse this JSON file using jackson?

I have this JSON file

{
  "personal": {
    "name": "John Doe",
    "age": "28",
    "gender": "male",
  }
}

This is the POJO I want to parse it to

public class customerInfo{
   private String infoType;
   private Map<String, String>;
}

The reason I want to use this POJO because the JSON file could also be

{
  "address": {
    "street": "123 main st",
    "state": "md",
    "zipcode": "21228"
  }
}

This is what I tried but it didn't work

customerInfo customer = mapper.readValue(new File("jsonTestFile.json"), customerInfo.class);

Any help please? Thank you!

how to convert a string with square bracket into lots of doubles in Java?

I want to know that how to convert a string I got from Jsonarray like this:

String lineStringJsonArray = "[[[0.093493,51.6037],[0.092077,51.6134],[0.075051,51.6179],[-0.247248,51.5166],[-0.259754,51.5235],[-0.28098,51.518],[-0.301457,51.515]]]"

to a list of doubles.

How should I use pattern to drop those square brackets?

Can someone help? thanks a lot!

Ajax call to REST service returns status:0

Ajax call from cordova android application to the REST service, returns

{ "readyState" : 0, "responseText" : "", "statusText" : "error" }

I've added <access origin="*" /> to the config.xml

    $.ajax({        
        type: "POST",    
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(dataObject),
        url: "http://ift.tt/1KGirAu",
        success: function(result){            
            if(result.auth){ 
                window.localStorage["authentication"] = result.authCode;
                window.localStorage["authDetails"] = result.details;                                    
                $.mobile.changePage("#home");    
            }                
            else{
                navigator.notification.alert('Login failed. Try again.', function() {});                        
            }
        },
        error: function(err){
            navigator.notification.alert('Error occurred unexpectedly.' + JSON.stringify(err) , function() {});
        }    
    });

The service is running in the localhost. I'm using GenyMotion as the Emulator.

Java get JSON file, Where did I do wrong?

I am a novice to Android Development and Java, I am a C# Developer. I cannot debug through this. I tried to get the System.out.println to spit out the exception message and stack trace but they are not working for some reason.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.util.Date;
import java.net.URL;
import org.json.JSONObject;

public class Weather {

public Base Base = new Base();
public Cloud Cloud = new Cloud();
public Coord Coord = new Coord();
public Info Info = new Info();
public Location Location = new Location();
public Temperature Temperature = new Temperature();
public Wind Wind = new Wind();

public Boolean fetch(String location) {

    try {

        String urlString = "http://ift.tt/1jfvxJq" + location + "&units=metric";
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        BufferedReader reader = new BufferedReader( new InputStreamReader ( connection.getInputStream() ) );
        StringBuffer json = new StringBuffer(1024);
        String tmp = "";
        while ( ( tmp = reader.readLine() ) != null )
            json.append(tmp).append("\n");
        reader.close();
        JSONObject data = new JSONObject( json.toString() );
        if (data.getInt("cod") != 200) {

            throw new Exception("cod is not 200");

        } else {

            Base.base = data.getString("base");

            Cloud.Value = data.getJSONObject("clouds").getInt("all");

            Coord.lat = data.getJSONObject("coord").getDouble("lat");
            Coord.lon = data.getJSONObject("coord").getDouble("lon");

            // Array Processing
            JSONObject id = data.getJSONArray("weathr").getJSONObject(0);
            JSONObject main = data.getJSONArray("weather").getJSONObject(1);
            JSONObject description = data.getJSONArray("weather").getJSONObject(2);
            JSONObject icon = data.getJSONArray("weather").getJSONObject(3);

            Info.description = description.getString("description");
            Info.icon = icon.getString("icon");
            Info.id = id.getInt("id");
            Info.main = main.getString("main");

            Location.cod = data.getInt("cod");
            Location.dt = new Date((long) data.getInt("dt") * 1000);
            Location.country = data.getJSONObject("sys").getString("country");
            Location.id = data.getInt("id");
            Location.message = data.getJSONObject("sys").getDouble("message");
            Location.name = data.getString("name");
            Location.sunrise = new Date((long) data.getJSONObject("sys").getInt("sunrise"));
            Location.sunset = new Date((long) data.getJSONObject("sys").getInt("sunset"));

            Temperature.humidity = data.getJSONObject("main").getInt("humidity");
            Temperature.max = data.getJSONObject("main").getInt("temp_max");
            Temperature.min = data.getJSONObject("main").getInt("temp_min");
            Temperature.pressure = data.getJSONObject("main").getInt("pressure");
            Temperature.temp = data.getJSONObject("main").getInt("temp");

            Wind.deg = data.getJSONObject("wind").getInt("deg");
            Wind.speed = data.getJSONObject("wind").getDouble("speed");

        }

        return true;        

    } catch (Exception ex) {

        System.out.println("Mayday, " + ex.getMessage().toString() +  ex.getStackTrace().toString());
        return false;

    }
}

So, how can I fix this, Can you also provde a better way to debug..

UPDATE:- I got the StackTrace out but I cannot understand why the error is happening. Can you guys explain this

08-01 00:41:05.010: W/System.err(8557): android.os.NetworkOnMainThreadException
08-01 00:41:05.010: W/System.err(8557):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
08-01 00:41:05.010: W/System.err(8557):     at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
08-01 00:41:05.010: W/System.err(8557):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
08-01 00:41:05.010: W/System.err(8557):     at java.net.InetAddress.getAllByName(InetAddress.java:214)
08-01 00:41:05.010: W/System.err(8557):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
08-01 00:41:05.010: W/System.err(8557):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
08-01 00:41:05.010: W/System.err(8557):     at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:341)
08-01 00:41:05.010: W/System.err(8557):     at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
08-01 00:41:05.010: W/System.err(8557):     at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
08-01 00:41:05.010: W/System.err(8557):     at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:315)
08-01 00:41:05.010: W/System.err(8557):     at libcore.net.http.HttpEngine.connect(HttpEngine.java:310)
08-01 00:41:05.010: W/System.err(8557):     at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:289)
08-01 00:41:05.010: W/System.err(8557):     at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:239)
08-01 00:41:05.010: W/System.err(8557):     at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:273)
08-01 00:41:05.020: W/System.err(8557):     at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:168)
08-01 00:41:05.020: W/System.err(8557):     at antu.mango.weather.Weather.fetch(Weather.java:27)
08-01 00:41:05.020: W/System.err(8557):     at antu.mango.drizzle.MainActivity.onCreate(MainActivity.java:26)

Getting JSON from URL getting NullPointerException when creating array of objects from JSON

I am building a datasource for my app that pulls in JSON from our website and then creates an array of custom objects. However, after I get the JSON, and loop through the objects to create my own, I am getting a NullPointerException error.

Method for getting JSON from URL:

public static JSONObject getJSONObjectfromURL(String url)
    {
        InputStream mIs = null;
        String result = "";
        JSONObject jObjectLogin = null;
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpGet httppost = new HttpGet(url);

            // Credentials
            String credentials = username + ":" + password;
            String credBase64 = Base64.encodeToString(credentials.getBytes(), Base64.DEFAULT).replace("\n", "");

            httppost.setHeader("Authorization", "Basic "+credBase64);

            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            mIs = entity.getContent();
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            BufferedReader bufferReader = new BufferedReader(new InputStreamReader(mIs,"iso-8859-1"),8);
            StringBuilder stringBuilder = new StringBuilder();
            String line = null;
            while ((line = bufferReader.readLine()) != null) {
                if(line.trim().equals("\n"))
                    continue;
                stringBuilder.append(line + "\n");
            }
            mIs.close();
            result=stringBuilder.toString();
        }catch(Exception e){
            Log.e("log_tag", "Error converting result "+e.toString());
        }
        try {
            jObjectLogin = new JSONObject(result);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return jObjectLogin;
    }

Method for creating my custom objects from JSON:

public static ArrayList<PUCObjects.PUCNewsItem> getPUCNews(boolean isArchives, String assetId) throws IOException, JSONException {

    int maxPerPage = 10;

    String url;
    if (isArchives) {
        url = "http://ift.tt/1KGgu73"+maxPerPage+"&rootId="+assetId;
    } else {
        url = "http://ift.tt/1KGgu73"+maxPerPage;
    }

    JSONObject json = getJSONObjectfromURL(url);
    JSONArray jsonData = json.getJSONArray("data");
    ArrayList<PUCObjects.PUCNewsItem> items = new ArrayList<PUCObjects.PUCNewsItem>();
    PUCObjects.PUCNewsItem item = null;

    for (int i = 0; i < jsonData.length(); i++) {

        JSONObject jsonObject = jsonData.getJSONObject(i);

        item = new PUCObjects.PUCNewsItem();
        item.title = jsonObject.getString("title");
        item.summary = jsonObject.getString("summary");
        item.body = jsonObject.getString("body");
        item.author = jsonObject.getString("author");
        item.assetId = jsonObject.getString("asset_id");

        // Images
        JSONArray images = jsonObject.getJSONArray("images");
        for (int a = 0; a < images.length(); a++) {

            JSONObject imageObject = images.getJSONObject(a);
            item.imageUrlSmall = imageObject.getString("thumb_small");
            item.imageUrlMedium = imageObject.getString("thumb_large");
            item.imageUrlLarge = imageObject.getString("url");
            item.imageUrlExtraLarge = imageObject.getString("url_large");

            // Check to see if we have a high res image. If not, use the next largest image.
            if (item.imageUrlExtraLarge.length() == 0) {
                item.imageUrlExtraLarge = item.imageUrlLarge;
            }

        }

        // Date
        String createdDate = jsonObject.getString("created_date");
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd-H:m");
        Date date = null;
        try {
            date = format.parse(createdDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        DateFormat df = new DateFormat();
        if (date != null) {
            item.created_date = df.format("MMMM d, yyyy", date).toString();
        }

        items.add(item);

    }

    return items;

}//end

Logcat:

07-31 13:37:38.280  20132-20132/com.puc.mobile E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.NullPointerException
            at com.puc.mobile.news.PUCNewsListAdapter.getCount(PUCNewsListAdapter.java:54)
            at android.widget.ListView.setAdapter(ListView.java:466)
            at com.puc.mobile.news.PUCNewsList$DownloadPUCNews.onPostExecute(PUCNewsList.java:181)
            at com.puc.mobile.news.PUCNewsList$DownloadPUCNews.onPostExecute(PUCNewsList.java:159)
            at android.os.AsyncTask.finish(AsyncTask.java:631)
            at android.os.AsyncTask.access$600(AsyncTask.java:177)
            at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4950)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1004)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:771)
            at dalvik.system.NativeStart.main(Native Method)

For some reason I am getting a NullPointerException when I am trying to display the results in a table. Having a feeling that for some reason items is coming back null, but not sure why.

Any ideas?

Express.js route and regex

I have an object like this :

geo: {
        description: 'Geolocalisation',
        properties: {
            latitude: {type: 'number'},
            longitude: {type: 'number'}
        }
    }

I want to create routes to retrive a nested object like :

host/geo.schema or host/geo.json

to get the entire object

host/geo/properties.schema or host/geo/properties.json

to get

properties: {
            latitude: {type: 'number'},
            longitude: {type: 'number'}
        }

obtain values to json file

I am making an application in vb net, and read JSON format files. I know how, but I have a file that has a different format, you can see here:

{
  "objects": {
    "realms/lang/de_DE.lang": {
      "hash": "729b2c09d5c588787b23127eeda2730f9c039194",
      "size": 7784
    },
    "realms/lang/cy_GB.lang": {
      "hash": "7b52463b2df4685d2d82c5d257fd5ec79843d618",
      "size": 7688
    },
    "minecraft/sounds/mob/blaze/breathe4.ogg": {
      "hash": "78d544a240d627005aaef6033fd646eafc66fe7a",
      "size": 22054
    },
    "minecraft/sounds/dig/sand4.ogg": {
      "hash": "37afa06f97d58767a1cd1382386db878be1532dd",
      "size": 5491
    }
  }
}

It is different because all text has objects, no string, so I can not read it defined classes. I just need the values of "hash", then add them to a textbox. I hope you can help me.

Newtonsoft Json date at different timezones

I am working on newton.json date convertions. I got stuck, unable to confirm if newtonsoft json serialize and deserialize convert dates based on local time zone.

Example: App sends date in IST time zone eg: 8/1/2015 Early Hrs, it is getting saved as 7/31/2015 evening times since the server is in PST time.

So newtonsoft json converts date to where time is getting deserialized? IF that is the case, then when that date is send back to APP it does not match.

Could you please tell me how newtonsoft date convert.serialize and Newtonsoft.Json.JsonConvert.SerializeObject timezones work.

Get AJAX Request and Looping Through JSON

I am using a GET ajax request to retrieve some JSON data from the database. I want to loop through it and print certain items. For example, I want to print all the address in stylist_1 only. The problem is that it only prints the last item.

Here's what the code looks like:

var stylist1Addresses;

    function getData() {
        $.ajax({
            url: '/getData',
            type: 'GET',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            async: false,
            success: function (data) {
                for (var i = 0; i < data.stylist_1.length; i++) {
                    stylist1Addresses = data.stylist_1[i];
                }
            }
        });
        console.log(stylist1Addresses);
    }

Sample data:

{
  "stylist_1": [
    {
      "Address": "1 Stn Main", 
      "Phone": "403-990-9033"
    }, 
    {
      "Address": "474 Cirrus Rd", 
      "Phone": "403-995-3243"
    }, 
    {
      "Address": "1591 Stn St", 
      "Phone": "403-982-8893"
    }
  ], 
  "stylist_2": [
    {
      "Address": "219 Welch Blvd", 
      "Phone": "587-436-3171"
    }, 
    {
      "Address": "374 Main Rd", 
      "Phone": "587-315-9431"
    }, 
    {
      "Address": "564 Main Rd", 
      "Phone": "403-938-9983"
    }
  ]
}

Do you always need a domain model for a web service?

I am creating a web service that will be hosted in IIS using the WebApi V2 framework. The web service exposes a local service provided locally by a .dll. The interface of the local service is very simple. I am following RESTful architectural constraints, and we don't have a need to store data on a database or persist the data. The response from the local service is a string that I will simply filter and parse into a JSON object before returning it back to the client. Is this cool?

Why json_encode() doesn't work if the number of elements in the array more then 3

I have an array that contains the following elements:

array(4) {
[0]=> array(2) { ["home"]=> string(5) "Niort" ["away"]=> string(12) "Valenciennes" } 
[1]=> array(2) { ["home"]=> string(15) "Kuban Krasnodar" ["away"]=> string(3) "Ufa" } 
[2]=> array(2) { ["home"]=> string(17) "Fratangelo, Bjorn" ["away"]=> string(13) "Bhambri, Yuki" } 
[3]=> array(2) { ["home"]=> string(13) "VfL Wolfsburg" ["away"]=> string(15) "Bayern Mnchen" } } 

and i'm trying to convert it to json array with:

while ($row = $result->fetch_assoc()) {
        array_push($events, $row);
    }
echo json_encode($events);

but it does not work, however, when i reduce the number of elements to 3 or less, it's work perfectly. Please, help me to understand why is this so, and if it is possible, let me know how i can convert more then 3 elements of my array.

How to make options for Google extensions

Recently, I've started learning how to make Google extensions. My problem is that I don't know how to make a button in which I click on it, show me options of extension like this: http://ift.tt/1DWHgDd. I didn't find any result. Is there any tutorial which shows how to make this button?

P.s. the icon of my extension appear, but nothing happens when I click on it. here is the code of manifest.json:

{ "name": "Extension Name", "version": "0.1.1.2", "description": "Extension's description", "manifest_version": 2, "options_page": "options.html", "background": { "page": "index.html" }, "browser_action": { "name": "Manipulate DOM", "icons": { "128":"icon.png" }, "default_icon": "icon.png" }, "content_scripts": [ { "js": [ "js-resource.js" ], "matches": [ "http://*/*", "https://*/*"] }] }

How to access string object in array of JSON-array via PHP?

I have searched for almost 30 minutes and still can't find the answer for my problem. So, here is it: I have an JSON-file called "localeDE.l", now I'm trying to print the objects to the website, "locale_name"(type: string) works, but "translations"(type: array) won't work.

My JSON file:

"locale_name": "DE",
"translations": [
    {"Welcome": "Willkommen",
     "Goodbye": "Auf Wiedersehen"}
]

Here my PHP file:

$file = file_get_contents('localeDE.l');
$locale = json_decode($file);
print_r($locale);
echo "Locale=" . $locale->{'locale_name'};
echo "Translations:";
echo "  Welcome:" . $locale->{'translations'}->{'Welcome'};
echo "  Goodbye:" . $locale->{'translations'}->{'Goodbye'};

I also tried something like (...) $locale->{'translations.Welcome'}; etc. Can You help me?

- Felipe Kaiser

Having trouble with PHP and JSON

I have to create a JSON request in PHP based on this encoded JSON layout and I'm having difficulty preparing the request in the pre-encoded PHP. Any help would be greatly appreciated as what I am trying to put together does not see to be working:

{   
    "skin":"weborder",  
    "establishmentId":1,    
    "items":[{  
        "modifier_amount":0,    
        "modifieritems":[   

        ],  
        "initial_price":0.1,    
        "special_request":"",   
        "price":0.1,    
        "product":null, 
        "product_name_override":"Bag Charge",   
        "quantity":1,   
        "tax_amount":0, 
        "tax_rate":0,   
        "is_cold":false 
    },
    {   
        "modifier_amount":0.5,  
        "modifieritems":[{  
            "modifier":106, 
            "modifier_cost":0,  
            "modifier_price":0.5,   
            "qty":1,    
            "qty_type":0    
        }], 
        "initial_price":1.95,   
        "special_request":"",   
        "price":1.95,   
        "product":1,    
        "product_name_override":"Regular Coffee",   
        "quantity":1,   
        "tax_amount":0.197, 
        "tax_rate":8.75,    
        "is_cold":false 
    }], 
    "orderInfo":{   
        "created_date":"2014-­‐06-­‐11T18:52:44",   
        "pickup_time":"2014-­‐06-­‐11T19:22:44",    
        "tax":0.2,  
        "subtotal":2.55,    
        "final_total":2.55, 
        "surcharge":0,  
        "dining_option":0,  
        "call_name":"Joe Smith / Jun 11, 7:22pm / 1234567890"   
    },  
    "paymentInfo":{ 
        "type":3,   
        "phone":"1234567890",   
        "email":"joe@mail.com", 
        "first_name":"Joe", 
        "last_name":"Smith" 
    },  
    "notifications":[{  
        "skin":"weborder",  
        "type":"email",
        "destination":"joe@mail.com"    
    }]  
}

Here is the PHP I put together that is breaking:

$order_data = array(
            'skin' => 'weborder',   
            'establishmentId' => $establishment,
            'items' => array(
                'modifier_amount':0,    
                'modifieritems' => array(   
                    'modifier' => '106',    
                    'modifier_cost' => '0', 
                    'modifier_price' => '0.5',  
                    'qty' => '1',   
                    'qty_type' => '0'   
                ),  
                'initial_price' => '0.1',   
                'special_request' => '',    
                'price' => '0.1',   
                'product' => null,  
                'product_name_override' => 'Bag Charge',    
                'quantity' => '1',
                'tax_amount' => '0',    
                'tax_rate' => '0',  
                'is_cold"' => 'false'   
             ),
             'orderInfo' => array(
                'created_date' => '2014-­‐06-­‐11T18:52:44',    
                'pickup_time' => '2014-­‐06-­‐11T19:22:44', 
                'tax' => '0.2', 
                'subtotal' => '2.55',   
                'final_total' => '2.55',    
                'surcharge' => '0', 
                'dining_option' => '0', 
                'call_name' => 'Joe Smith / Jun 11, 7:22pm  / 1234567890'
             ),
             'paymentInfo' => array(
                'type' => 3,    
                'phone' => '1234567890',    
                'email' => 'joe@mail.com',  
                'first_name' => 'Joe',  
                'last_name' => 'Smith'  
             ),
             'notifications' => array(
                'skin:' => 'weborder',  
                'type' => 'email',
                'destination' => 'joe@mail.com'
             )
        );

        // Then use json_encode
        $json = json_encode($order_data);

Thanks in advance. :)  

Bad request on post json data in Angularjs and spring mvc

i want to post json data to spring mvc controller by Angularjs. For this purpose i wrote this code. but when i post form bad request error display in console.for simple data it work correctly but for nested object not work. how i post nested json object to controller?

my entity :

 public class TestData {
  private String name;
  private List<TestData2> data;
 }
 public class TestData2 {
   private String email;
   private String body;
 }

and in jsp page:

     <form ng-submit="add(ab)">
           <input type="text" ng-model="ab.name">   
           <input type="text" ng-model="ab.data[0].email">  
           <input type="text" ng-model="ab.dat[0].body">  
     </form>  

and in Angularjs controller:

  app.controller('myController', function ($scope, $http) {
    $scope.ab = {};
    $scope.addComment = function(ab) {
        console.log(ab);
        $http.post('/add', ab).success(function(response){}
    )};

How to create json in c# for php service

I'm creating php rest service which will be consumed by c# desktop application using HttpWebRequest class.

I would like to pass json to service with post method, and create associative array in php which I would use to process user request.

I have tried to send json as a string in different formats (ex. "{"x":"y"}" or "{'x':'y'}"), also to use JsonConvert.SerializeObject form Newtonsoft.Json to serialize object in application and tried to convert that to array using json_encode method. But it always keeps it as a string. I have even tried to change string from post in php to match format required by json_encode (ex. '{"x":"y"}') but can't do it.

So my question basically is how to format json in c# so I can use it in php script?

HTTParty is escaping JSON

I'm using HTTParty to send data to a remote API, however the API is complaining because the JSON being sent by HTTParty appears to be being escaped, and is thus deemed invalid.

Here's what I'm doing:

query = {"count"=>1,
 "workspaces"=>
  {123445=>
    {"title"=>"Test Project",
     "description"=>"",
     "start_date"=>"2015-06-01T00:00:00.000Z",
     "due_date"=>"2015-08-31T00:00:00.000Z",
     "price_in_cents"=>8000,
     "currency"=>"USD",
     "status_key"=>130,
     "custom_field_values_attributes"=>[],
     "workspace_groups_attributes"=>
      [{"created_at"=>"2015-07-13T11:06:36-07:00",
        "updated_at"=>"2015-07-13T11:06:36-07:00",
        "name"=>"Test Customer",
        "company"=>true,
        "contact_name"=>nil,
        "email"=>nil,
        "phone_number"=>nil,
        "address"=>nil,
        "website"=>nil,
        "notes"=>nil,
        "id"=>"530947",
        "custom_field_values_attributes"=>[]}],
     "id"=>123445}},
 "results"=>[{"key"=>"workspaces", "id"=>123445}]}

Calling to_json on query escapes the JSON too:

"{\"count\":1,\"workspaces\":{\"123445\":{\"title\":\"Test Project\",\"description\":\"\",\"start_date\":\"2015-06-01T00:00:00.000Z\",\"due_date\":\"2015-08-31T00:00:00.000Z\",\"price_in_cents\":8000,\"currency\":\"USD\",\"status_key\":130,\"custom_field_values_attributes\":[],\"workspace_groups_attributes\":[{\"created_at\":\"2015-07-13T11:06:36-07:00\",\"updated_at\":\"2015-07-13T11:06:36-07:00\",\"name\":\"Test Customer\",\"company\":true,\"contact_name\":null,\"email\":null,\"phone_number\":null,\"address\":null,\"website\":null,\"notes\":null,\"id\":\"530947\",\"custom_field_values_attributes\":[]}],\"id\":123445}},\"results\":[{\"key\":\"workspaces\",\"id\":123445}]}"

Is this expected behavior to escape the JSON? Or I'm wondering if the hash I'm building for query is invalid for JSON purposes?

Any help would be greatly appreciated.

Cannot save with AngularJS to Rails Backend

We are creating a "twitter clone" using Angular JS and Rails postgresql backend. We have a form to submit new content for a tweet. We have been using AngularJS Resource to grab jSON objects. This is the form below:

<section id="tweet-box" ng-controller="TweetController" action="/tweets" method="post">
    <p id="tweet-box-title">Compose New Tweet</p>
    <form id="tweet-form" ng-submit="addTweet()">
      <textarea id="new-tweet" cols="30" rows="5" maxlength="140" name="tweet" ng-model="content"></textarea>
      <button type="submit" value="Tweet">Add Tweet</button>
    </form>
</section> 

Here is our AngularJS Code. tweetApp is our entire App; the factory grabs our 50 most recent Tweets as jSON. The addTweet() function is what we're trying to have save our data to our database.

var tweetApp = angular.module("tweetApp", ['ngResource']);

tweetApp.factory("RecentTweets", function($resource)
{
  return $resource("/tweets/recent");
});

tweetApp.controller("TweetController", function($scope, RecentTweets)
{
  $scope.tweets = RecentTweets.query(function(data)
  {
    data;

  });
  $scope.addTweet = function(){
    if ($scope.content){
    $scope.tweet = new Tweet();
    $scope.tweet.content = $scope.content;

    // Tweet.save($scope.tweet);
    $scope.tweet.$save(function(msg, header){
    });
    }
    $scope.content = null;
  }
});

At the very end, $save vs .save both come up as not a function in our console. We have tried Tweet.save as well as $scope.content.$save as well as other iterations. Please advise. Thanks!

Convert swift arrays into JSON object

I have two arrays :

let value = [41, 42, 45] ...
let date = [NSDate1, NSDate2, NSDate3] ...

I need to save the data as a json object onto our mongodb on the server. I tested with a sample object formatted as below and it worked as expected. How can I reformat my arrays into this format efficiently in swift/objective c?

let jsonObject = [
["date" : "2014/01/01", "value" : "41"],
["date" : "2014/01/02", "value" : "42"],
["date" : "2014/01/03", "value" : "45"]]

Any help would be very much appreciated ! Thank you !

How do I populate an Android GridView with a JSON image Array?

I want to display JSON images in gridview. I will keep all JSON data and the url semi-changed for data-integrity purposes.

I am receiving the logging error:

Could not load image from/images/image.php?w=100....".

I believe that the image information is not being correctly gathered by populate the JSON array, but I am uncertain.

public class JSONImageViewer extends Activity {

  private GridView gridV;
  private ImageAdapter imageAdapter;

  public int currentPage = 1;
  public int TotalPage = 0;

  public Button btnNext;
  public Button btnPre;

  private final static String TAG_IMG = "CarImageLink";

  ArrayList<HashMap<String, Object>> MyArrList = new ArrayList<HashMap<String, Object>>();

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // ProgressBar
    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

    setContentView(R.layout.activitymain);

    // GridView and imageAdapter
    gridV = (GridView) findViewById(R.id.gridView1);
    gridV.setClipToPadding(false);
    imageAdapter = new ImageAdapter(getApplicationContext());
    gridV.setAdapter(imageAdapter);

    // Next
    btnNext = (Button) findViewById(R.id.btnNext);
    btnNext.setOnClickListener(new View.OnClickListener() {
      public void onClick(View v) {
        currentPage = currentPage + 1;
        ShowData();
      }
    });

    // Previous
    btnPre = (Button) findViewById(R.id.btnPre);
    btnPre.setOnClickListener(new View.OnClickListener() {
      public void onClick(View v) {
        currentPage = currentPage - 1;
        ShowData();
      }
    });

    // Show first load
    ShowData();

  }

  public void ShowData() {
    btnNext.setEnabled(false);
    btnPre.setEnabled(false);

    setProgressBarIndeterminateVisibility(true);
    new LoadContentFromServer().execute();
  }

  class LoadContentFromServer extends AsyncTask<Object, Integer, Object> {

    @Override
    protected Object doInBackground(Object... params) {

      String url = "http://auto.com";

      // JSONArray data;
      JSONObject data;
      try {

        // data = new JSONArray(getJSONUrl(url));
        data = new JSONObject(getJSONUrl(url));
        JSONArray dataArray = data.getJSONArray("car_images");
        MyArrList = new ArrayList<HashMap<String, Object>>();
        HashMap<String, Object> map;

        /*
         * TotalRows = Show for total rows TotalPage = Show for total page
         */

        int displayPerPage = 9; // Per Page
        int TotalRows = data.length();
        int indexRowStart = ((displayPerPage * currentPage) - displayPerPage);

        if (TotalRows <= displayPerPage) {
          TotalPage = 1;
        } else if ((TotalRows % displayPerPage) == 0) {
          TotalPage = (TotalRows / displayPerPage);
        } else {
          TotalPage = (TotalRows / displayPerPage) + 1;
          TotalPage = (int) TotalPage;
        }
        int indexRowEnd = displayPerPage * currentPage;
        if (indexRowEnd > TotalRows) {
          indexRowEnd = TotalRows;
        }

        for (int i = 0; i < dataArray.length(); i++) {
          map = new HashMap<String, Object>();
          JSONObject c = dataArray.getJSONObject(i);

          // Thumbnail Get ImageBitmap To Object
          Bitmap newBitmap = loadBitmap(c.getString(TAG_IMG));
          map.put(TAG_IMG, newBitmap);

          MyArrList.add(map);
          // publishProgress(i);
        }

      } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      return null;
    }

    @Override
    public void onProgressUpdate(Integer... progress) {
      imageAdapter.notifyDataSetChanged();
    }

    @Override
    protected void onPostExecute(Object result) {

      // Disabled Button Next
      if (currentPage >= TotalPage) {
        btnNext.setEnabled(false);
      } else {
        btnNext.setEnabled(true);
      }

      // Disabled Button Previous
      if (currentPage <= 1) {
        btnPre.setEnabled(false);
      } else {
        btnPre.setEnabled(true);
      }

      setProgressBarIndeterminateVisibility(false); // When Finish
    }
  }

  class ImageAdapter extends BaseAdapter {

    private Context mContext;

    public ImageAdapter(Context context) {
      mContext = context;
    }

    public int getCount() {
      return MyArrList.size();
    }

    public Object getItem(int position) {
      return MyArrList.get(position);
    }

    public long getItemId(int position) {
      return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
      // TODO Auto-generated method stub

      LayoutInflater inflater = (LayoutInflater) mContext
          .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

      if (convertView == null) {
        convertView = inflater.inflate(R.layout.activity_column, null);
      }

      // ColPhoto
      ImageView imageView = (ImageView) convertView.findViewById(R.id.ColPhoto);
      imageView.getLayoutParams().height = 60;
      imageView.getLayoutParams().width = 60;
      imageView.setPadding(5, 5, 5, 5);
      imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
      try {
        imageView.setImageBitmap((Bitmap) MyArrList.get(position).get(
            "CarImageLink"));
        // Log.v("MyArrList2", MyArrList.toString());
      } catch (Exception e) {
        // When Error
        imageView.setImageResource(android.R.drawable.ic_menu_report_image);
      }

      return convertView;

    }

  }

  /*** Get JSON Code from URL ***/
  public String getJSONUrl(String url) {

    StringBuilder str = new StringBuilder();
    HttpClient client = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(url);

    try {
      HttpResponse response = client.execute(httpGet);
      StatusLine statusLine = response.getStatusLine();

      int statusCode = statusLine.getStatusCode();

      if (statusCode == 200) {
        // Download OK
        HttpEntity entity = response.getEntity();
        InputStream content = entity.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(
            content));
        String line;

        while ((line = reader.readLine()) != null) {
          str.append(line);
        }
      } else {
        Log.e("Log", "Failed to download file..");
      }
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return str.toString();
  }

  /***** Get Image Resource from URL *****/
  private static final String TAG = "ERROR";
  private static final int IO_BUFFER_SIZE = 4 * 1024;

  public static Bitmap loadBitmap(String url) {

    Bitmap bitmap = null;
    InputStream in = null;
    BufferedOutputStream out = null;

    try {
      in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);

      final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
      out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
      copy(in, out);
      out.flush();

      final byte[] data = dataStream.toByteArray();
      BitmapFactory.Options options = new BitmapFactory.Options();
      options.inSampleSize = 1;

      bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options);
    } catch (IOException e) {
      Log.e(TAG, "Could not load image from" + url);
    } finally {
      closeStream(in);
      closeStream(out);
    }

    return bitmap;
  }

  private static void closeStream(Closeable stream) {
    if (stream != null) {
      try {
        stream.close();
      } catch (IOException e) {
        android.util.Log.e(TAG, "Could not close stream", e);
      }
    }
  }

  private static void copy(InputStream in, OutputStream out) throws IOException {
    byte[] b = new byte[IO_BUFFER_SIZE];
    int read;
    while ((read = in.read(b)) != -1) {
      out.write(b, 0, read);
    }
  }
}

Sample array:

{"car_images":[{"id":1,"CarImageID":"4".."CarImageLink:"plk.jpg"....

Any suggestions of why this error is occurring? Because of array population issues? Please explain and show examples relating to my code.

Jquery Ajax call to java rest api success function is not firing

I am trying to send HTML form data as a JSON to java rest api and it generates response as JSON. Here is my code.

HTML FORM:

<html>
<body>
<form action ="" method= "post" name= "testform">
    <p> Balance : <input type="text" id="balance" name="balance" /></p>
    <p>Pin : <input type="text" id="pin" name="pin" /></p>
    <p>CardID : <input type="text"  id="cardId" name="cardId" /></p>
    <input type ="submit" id="add-account" value="add user"></input>
</form>
<script src="http://ift.tt/1yCEpkO"></script>
<script src="js/main.js"></script>
</body>
</html>

Jquery CODE:

$(function(){
console.log("Jquery called");
$('#add-account').click(function(event){
    event.preventDefault();
    var balance = $("#balance").val();
    var pin = $("#pin").val();
    var cardId = $("#cardId").val();
    var firstcall = 
    $.ajax({
        type: "POST",
        url: "http://localhost:8081/quickpay/webapi/myresource",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({
            "balance":balance,
            "pin": pin,
            "cardId": cardId
        }), 
        dataType: "json",
        success:function (successResponse,textStatus,jqXHR) {
            alert("first api");         
        },
        error: function (errorResponse1) {
            console.log(errorResponse1);
            alert("failed first api");
        }
    });
});
});

JAVA REST API:

@Path("myresource")
public class MyResource {
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Account createAccount(Account acc){
        Account account =  AccountService.createAccount(acc.getBalance(),acc.getPin(),acc.getCardId());
        return account;
    }
}

OUTPUT I'm getting is:

When I try to call the api in POSTMAN, it runs successfully and data is inserted successfully. When I try to click on ADD USER button , data is inserted into database successfully but ALERT messege of success function does not appear.

I'm monitoring network tab of Google chrome, There I find this error in myresource status is cancelled and type is xhr.

When hovering mouse on Jquery.min.js I get this..

n.ajaxTransport.k.cors.a.crossDomain.send @ jquery.min.js:4

n.extend.ajax @ jquery.min.js:4

(anonymous function) @ main.js:9

n.event.dispatch @ jquery.min.js:3

n.event.add.r.handle @ jquery.min.js:3

Problem : How can I make success function of ajax call working ?? Where I'm going wrong.?

EDIT: I added preventDefault() method. So Now It is working!

Spring RestTemplate and JSON how to ignore empty Arrays deserialization?

I am currently using Spring 4.1.6 with a RestTemplate to consume a third party webservice with JSON which I cannot change its behavior.I am using Jackson databind v2.6.0.

Problem: Sometimes the service returns for a member a hashmap {member:{"key":"value",...}} sometimes the same member is just an empty array {member:[]}. So I can not ignore the property by default.

Is there a way to configure the deserialization to ignore empty arrays? I saw a jackson property "WRITE_EMPTY_JSON_ARRAYS" but I am not quite sure how I can use it with my restTemplate and spring configuration.

Are there other possiblities e.g. use some combination of @JsonXXX Annotations? I saw @JsonSerialize which can be used on class level, but I don't like to write a deserializer for all my classes just to handle this situation (However if there is no other way of course I will do)

Example responses to llustrate the behavior of the service:

  • response with a hashmap {"id":170,"categories":{"13":"caro"}}

  • response with empty array of the same member {"id":170,"categories":[]}

Example of my RestTemplate usage:

    BasicAuthRequestFactory requestFactory = new BasicAuthRequestFactory(httpClient);        
    restTemplate = new RestTemplate(requestFactory);
    Article a = restTemplate.getForObject(new URI("http://..."), Article.class);

Error:

 caused by: com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.LinkedHashMap out of START_ARRAY token
 at [Source: java.io.PushbackInputStream@4aa21f9d; line: 1, column: 1456] (through reference chain: ResponseArticleWrapper["data"]->Article["categories"])
 at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:148)

Example of my current annotated class:

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(Include.NON_NULL)
public class Article {  
    @JsonProperty("id")
    private Integer id;
    @JsonProperty("categories")  
    private Map<Integer,String> categories = new HashMap<Integer,String>();
}

Thank you in advance for any hints and examples.

How to convert thrift objects to readable string and convert it back?

Sometimes, we need to create some thrift objects in unit tests. We can do it by manually create object using Java code, like:

MyObj myObj = new MyObj();
myObj.setName("???");
myObj.setAge(111);

But which is not convenient. I'm looking for a way to create objects with some readable text.

We can convert thrift objects to JSON with TSimpleJSONProtocol, and get very readable JSON string, like:

{ "name": "???", "age": 111 }

But the problem is TSimpleJSONProtocol is write only, thrift can't read it back to construct an instance of MyObj.

Although there is a TJSONProtocol which supports to serialize and deserialize, but the generated JSON is not readable, it uses a very simplified JSON format and most of the field names are missing. Not convenient to construct it in tests.

Is there any way to convert thrift objects to readable string and also can convert it back? If TSimpleJSONProtocol supports converting back, which is just what I'm looking for