dimanche 28 juin 2015

how to run simple ODATA query dynamically and return result in json format using with Roslyn?

I'm working on query builder for simple Odata

I'm generating simple odata queries dynamically and want to show result of queries on json format.

query text:

   var DetailData = await myClient.For<CustomerDetail>().Filter(q => q.Id == id).OrderBy(q => q.Key).FindEntriesAsync();

how to run simple ODATA query dynamically and return result in json format?

Swift Haneke: Json Data in TextView

I used the Haneke Framework to get Data from a Site. With the Haneke Framework i also can get Images from a site, and these Images i can present on a UIImageView. Now i wanted to get some text from a site.

I did it like this:

 cache.fetch(URL: URL).onSuccess { JSON in
            println(JSON.dictionary?["index"])

It printed me all the data from "Index".

Now i want, that all the data from "Index" should be presented on a UITextView.

  self.textView.text = JSON.dictionary["index"]

But it doesn't work..

I get the error: Cannot assign a value of type 'AnyObject' to a value of type 'String!'

I have to unwrap it or?

How do I access the element title in the Json?

I want GET json from http://omadbapi.com/?s= for search script, but I'm having trouble with get Title elment in this JSON :

{
"Search": [
{
  "Title": "Sherlock Holmes: A Game of Shadows",
  "Year": "2011",
  "imdbID": "tt1515091",
  "Type": "movie"
},
{
  "Title": "Spy Kids 3-D: Game Over",
  "Year": "2003",
  "imdbID": "tt0338459",
  "Type": "movie"
}
]
}

JavaScript :

$(document).ready(function () {
    var url = 'http://www.omdbapi.com/?',
        mode = 's=',
        input,
        movieName;

    $('button').click(function() {
        var input = $('#movie').val(),
        movieName = encodeURI(input);

        $.getJSON( url + mode + input, function( data ) {

          $.each(data, function(e,p) {
            document.getElementById("item").innerHTML="Title : " + p.Title;
          });
    });
    });
});

p.Title or data.Title, I don't know...

"No matching records found" NOT displayed in "bootstrap-table"

I am using the "bootstrap-table" plugin for my website and currently using it's server side pagination properties.

The table is being populated correctly and the search feature also works. BUT when something not present is searched for it displays all the records instead of displaying "No matching records found".

This is the html code I am using...

<table data-toggle="table"
       data-url="1.php"
       data-pagination="true"
       data-side-pagination="server"
       data-page-list="[5, 10, 20, 50, 100, 200]"
       data-search="true"
       data-height="300">
    <thead>
    <tr>
        <th data-field="state" data-checkbox="true"></th>
        <th data-field="memberID" data-align="right" data-sortable="true">Member ID</th>
        <th data-field="name" data-align="center" data-sortable="true"> Name</th>
        <th data-field="dob" data-sortable="true">Date of Birth</th>
    </tr>
    </thead>


</table>

and this is the php script I am using to create the JSON response...

<?php

require_once('db-connect.php');

if(isset($_GET["limit"])) {
    $limit = $_GET["limit"];
} else {
    $limit = 10;
}

if(isset($_GET["offset"])) {
    $offset = $_GET["offset"];
} else {
    $offset = 0;
}

if(isset($_GET["sort"])) {
    $sort = $_GET["sort"];
} else {
    $sort = "";
}

if(isset($_GET["order"])) {
    $order = $_GET["order"];
} else {
    $order = "asc";
}

 if(isset($_GET["search"])) {
    $search = $_GET["search"];
 } else {
    $search = "";
 }


if($search == "") {
    $result = mysqli_query($connection,"select memberID, name, dob from memberdetails" );
} else {

    $result = mysqli_query($connection,"select memberID, name, dob from memberdetails WHERE memberID LIKE '%$search%'"  );
}


$row = array();

if ( mysqli_num_rows($result) > 0 ) {
            while($row = mysqli_fetch_assoc($result)) {
                $result_2d_arr[] = array (  'memberID' => $row['memberID'],
                                            'name' => $row['name'],
                                            'dob' => $row['dob']);
            }




//get the result size
$count = sizeof($result_2d_arr);

//order the array
if($order != "asc") {
    $result_2d_arr = array_reverse($result_2d_arr);
}

//get the subview of the array
$result_2d_arr = array_slice($result_2d_arr, $offset, $limit);



echo "{";
echo '"total": ' . $count . ',';
echo '"rows": ';
echo json_encode($result_2d_arr);
echo "}";

}

?>

The JSON response is as follows...

{"total": 23,"rows": [{"memberID":"1","name":"asd","dob":"2015-06-03"},{"memberID":"2","name":"asd","dob":"2015-06-03"},{"memberID":"3","name":"asd","dob":"2015-06-03"},{"memberID":"4","name":"asd","dob":"2015-06-03"},{"memberID":"5","name":"asd","dob":"2015-06-03"},{"memberID":"6","name":"asd","dob":"2015-06-03"},{"memberID":"7","name":"asd","dob":"2015-06-03"},{"memberID":"8","name":"asd","dob":"2015-06-03"},{"memberID":"9","name":"asd","dob":"2015-06-03"},{"memberID":"10","name":"asd","dob":"2015-06-03"}]}

Handle Post Data of JSON in PHP

I receive JSON post data ....

{"split_info":"17076370","customerName":"Lahoti","status":"failed","error_Message":"fail.","paymentId":"17076370","productInfo":"productInfo","customerEmail":"cxxxx.xx@gmail.com","customerPhone":"999999999","merchantTransactionId":"BR121","amount":"19.0","notificationId":"443"}

I have written PHP code to Update my Database using merchantTransactionId received as JSON post data. My database is not going to update... My php code is as below Please help..

<?php
include("dbconnection.php");
if(isset($_POST))
{
$json_a = json_decode($_POST, true);
 $Id=$json_a['merchantTransactionId'];
 $status="payUMoney";
 mysql_query("UPDATE std status= '".$payStatus."' WHERE Id='".$Id."'",$db);
?>

POST raw json code ios

i'm new to ios developing and i want to ask how can i post a raw json code to the server.

For Example: i want to send this JSON raw data to http://example.com/user

{ "user": 
                {   "username": "jkaaannyaad11",
                    "password": "secret123456",
                    "gender": "male",
                    "first_name": "assd",
                    "last_name": "ffsasd",
                    "birth_date": "can be null",
                    "phone_number": "12343234",
                                                                  "have_car":"1",
                                                                  "same_gender" :"0",
                                                                  "uid": "this is id for facebook , can be null"
                },
            "home": {
                    "longitude": "31.380301",
                    "latitude": "30.054272",
                    "name": "city"
                    },
            "work": {
                    "longitude": "30.068237",
                    "latitude": "31.024275",
                    "name": "village"
                    },
            "email": {
                    "email_type": "work",
                    "email": "hello.me@me.com"
                    }
            }

so how can i do it ?

Dearest Regards,

How can i parse json array?

I am building an Android app and i need to populate a custom listview with some data from my localhost. I am trying to use volley JsonArrayRequest to get that data under the format of a JSONObject array but all i get is org.json.JSONException: End of input at character 0 of. This is my json array request :

final String URL = "http://ift.tt/1TXdybA";
        JsonArrayRequest productsReq = new JsonArrayRequest(Method.POST, URL, new Listener<JSONArray>() {

            @Override
            public void onResponse(JSONArray response) {
                Log.d("productTAG", response.toString());
                for(int i = 0; i < response.length(); i++)
                {
                    try 
                    {   
                        JSONObject productObj = response.getJSONObject(i);
                        String title = productObj.getString("title");
                        String description = productObj.getString("description");
                        String category = productObj.getString("category");
                        String subCategory = productObj.getString("subCategory");
                        String size = productObj.getString("size");
                        String price = productObj.getString("price");
                        String thumbnailUrl = productObj.getString("image_one");

                        Product product = new Product(title, thumbnailUrl, description, category, subCategory, size, price);
                        products.add(product);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

            }
        }, new ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("products_error", error.getMessage().toString());
                error.printStackTrace();
            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();

                params.put("req", "products");
                params.put("category", category);
                params.put("subCategory", subCategory);

                return params;
            }
        };
        VolleyCore.getInstance(getActivity()).addToRequestQueue(productsReq); 

The method i am using is POST and under the getParams i am adding a tag named req which has the value products. I am checking for this tag in index.php. This is my function that queries the table:

public function getItems($category, $subCategory)
    {
        $query = mysql_query("SELECT * FROM items WHERE category = '$category' AND sub_category = '$subCategory'") or die(mysql_error());


        $objects = array();
        if($query)
        {
            while($objects = mysql_fetch_assoc($query))
            {
                $final[] = $objects;
            }
        }
        return $final;

    }

Here in index.php i am checking for the request:

if(isset($_POST['req']) && $_POST['req'] == 'products')
    {
        $category = $_POST['category'];
        $subCategory = $_POST['subCategory'];


        $obj = $func->getItems($category, $subCategory);

        echo json_encode($obj);

    }

$func is the instantiation of the class where i keep all the methods working with the database(including getItems()). If i use volley StringRequest i do get a response back, but then again why don't i get the response while using JsonArrayRequest ? What am i doing wrong?

Parsing json with gson and java

I am struggling to parse a json output with Java and gson, but I am really stuck.

I would appreciate any suugestion.

This is my sample JSON file:

{
"sportId": 29,
"last": 26142386,
"league": [
    {
        "id": 1833,
        "events": [
            {
                "id": 383911973,
                "starts": "2015-01-22T21:00:00Z",
                "home": "America de Natal",
                "away": "Barras",
                "rotNum": "901",
                "liveStatus": 0,
                "status": "O",
                "parlayRestriction": 0
            },
            {
                "id": 383911974,
                "starts": "2015-01-22T21:00:00Z",
                "home": "Baraunas RN",
                "away": "ASSU RN",
                "rotNum": "904",
                "liveStatus": 0,
                "status": "O",
                "parlayRestriction": 0
            }
        ]
    }
  ]
}

My target is to a make a 2-dimensional array (or something similar) of the form:

leagueId, eventId, home, away
------------------------------
   1         1       a    b
   .         .       .    .
   .         .       .    .
  etc       etc     etc   etc

in order to insert the data in a MYSQL table.

I have write the following classes:

public class Fixtures {
int last;
int sportId;
ArrayList<Leagues> league = new ArrayList<Leagues>();

public ArrayList<Leagues> getListOfLeagues() {  
    return league;  
}  

public int getSportId(){
    return sportId;
}

 public int getLast(){
    return last;
 }

}

public class Leagues {
int id;
ArrayList<Events> events;

public int getLeagueId(){
    return id;
}

 public ArrayList<Events> getListOfEvents() {  
    return events;  
 }  

}

public class Events {
int id;
String home;
String away;


public int getEventId(){
    return id;
}

public String getHome() {  
    return home;  
}  

 public String getAway() {
    return away;
 }


}

and

Gson gson = new GsonBuilder().create();             
Fixtures fixture = gson.fromJson(jsonsource, Fixtures.class);
System.out.println(fixture.getSportId());
System.out.println(fixture.getLast());

ArrayList<Leagues> Leagues = fixture.getListOfLeagues();

Dont know how to proceed :(

Mapping a large json object (from rest service) to a smaller object? LoDash?

I am receiving a list of tweets (from a rest service) which is a really big list of many properties but I am only interested in a few properties in each item in the collection that is returned.

What is the best way of mapping this to a smaller object?

Does lodash help here?

I do I just iterate over it and create many new object?

Any help appreciated.

How to store data of dynamically generated Forms on Submit in Android?

I am developing a android application in which I am creating different dynamic form controls of different forms from the JSON data at runtime. The form may contain EditText, Spinner, Chechboxlist, Radiobuttonlist or five Addressboxes of EditText. Each control may also appear multiple times in different order. Now, I have generated and displayed the form controls of different forms at runtime.

One Example Form :

TextBox1 : ___________

Spinner2 : Item1 Item2 Item3

TextBox3 : ___________

Checkbox4 :

  • Option1
  • Option2
  • Option3

Radiogroup5 :

  • Radio1
  • Radio2

Spinner6 : Item1 Item2

Checkbox7 :

  • Option1
  • Option2

Radiogroup8 :

  • Radio1
  • Radio2

Address9 : _____________ _____________ _____________ _____________ _____________

Here Address contains five EditText consecutively.Now other form may or may not contain this controls.Here TextBox1, Spinner2, TextBox3 etc are the unique label to identify the control. But my problem is to submit the data entered in the form. The form contains a submit button. By pressing it, I have to send POST JSON Request by form the JSON with the filled data.

Example JSON Request :

  { "FormData" : {
              {"Name":"TextBox1" , "Value":"DummyText"},
              {"Name":"Spinner2" , "Value":"Item3"},
              {"Name":"TextBox3" , "Value":"DummyText"},
              {"Name":"Checkbox4" , "Value":"Option2, Option3"},
              {"Name":"Radiogroup5" , "Value":"Radio2"},
              {"Name":"Spinner6" , "Value":"Item1"},
              {"Name":"Checkbox7" , "Value":"Option1"},
              {"Name":"Radiogroup8" , "Value":"Radio1"},
              {"Name":"Address9" , "Value":"Dummy1, Dummy2, Dummy3, Dummy4,Dummy5"} 



           }

So how to write the proper single code for storing and submitting that data for a particular dynamic form in a data structure in such a way that I can form that JSON Request? Thanks in advance.

Laravel 5 how to return a template with response()->json()?

Below is my database:

post:
id user_name content created_at

Below is my post controller:

public function new(Request $request){
        $data = $request->all();
        $post = new Post;
        $post->user_name = $data['name'];
        $post->message = $data['content'];
        $post->save();
        $id = $post->id;
        $show = Post::find($id)->first();
        // $html = view('wall.post')->with('post', $show);
        return response()->json(['success' => $post->id,'message'=> 'Post Sent', 'html' => $html]);
    }

and my /views/wall/post.blade.php :

<div class="ui post">
<div class="name">User : {{ $post->user_name }}</div>
<div class="content">{{ $post->content }}</div>
</div>

Below is my question:

how do i get the content from post.blade.php with user_name and content return as below to $html in new() when i post name=kenny and content=testing:

<div class="ui post">
<div class="name">User : Kenny</div>
<div class="content">Testing</div>
</div>

and i just use jquery to prepend above code to my page?

Thanks

{Sorry if i got bad grammar in my english}

Select an arrray from JSON data on PHP

everyone!

I'm working on a movie website(which obviously not completed). I want to know how to export data from an API and select an array from JSON data on PHP. In this case, I want to output the title of the movie but it seems to not working. I get this error: Notice: Trying to get property of non-object. From the error, I know that I'm trying to output an object, not a string but I don't know how to resolve it.

Here's my index.php file:

<?php
require_once('includes/variables.php');
 ?>
 <!DOCTYPE html>
 <html>
    <body>
    <?php
        echo $movieNameList->data->movies[1]->id;
    ?>
</body>
</html>

includes/variables.php file:

 <?php
 $getMovieList = file_get_contents('http://ift.tt/1xsOjG3');
 $movieNameList = json_decode($getMovieList[0]);
 ?>

http://ift.tt/1xsOjG3 file if you're lazy:

{  
   "status":"ok",
   "status_message":"Query was successful",
   "data":{  
      "movie_count":4220,
      "limit":2,
      "page_number":1,
      "movies":[  
         {  
            "id":4247,
            "url":"https:\/\/yts.to\/movie\/rem-by-mtv-2014",
            "imdb_code":"tt4066748",
            "title":"R.E.M. by MTV",
            "title_long":"R.E.M. by MTV (2014)",
            "slug":"rem-by-mtv-2014",
            "year":2014,
            "rating":8,
            "runtime":107,
            "genres":[  
               "Documentary"
            ],
            "language":"English",
            "mpa_rating":"Unknown",
            "background_image":"https:\/\/s.ynet.io\/assets\/images\/movies\/rem_by_mtv_2014\/background.jpg",
            "small_cover_image":"https:\/\/s.ynet.io\/assets\/images\/movies\/rem_by_mtv_2014\/small-cover.jpg",
            "medium_cover_image":"https:\/\/s.ynet.io\/assets\/images\/movies\/rem_by_mtv_2014\/medium-cover.jpg",
            "state":"ok",
            "torrents":[  
               {  
                  "url":"https:\/\/yts.to\/torrent\/download\/1F28D13F40AE91AECC58D649F5F9D84D29321632.torrent",
                  "hash":"1F28D13F40AE91AECC58D649F5F9D84D29321632",
                  "quality":"720p",
                  "seeds":1063,
                  "peers":544,
                  "size":"812.23 MB",
                  "size_bytes":851680192,
                  "date_uploaded":"2015-06-28 08:49:09",
                  "date_uploaded_unix":1435438149
               },
               {  
                  "url":"https:\/\/yts.to\/torrent\/download\/DED26397FD36DFC932BB5EEEC82D25204699943C.torrent",
                  "hash":"DED26397FD36DFC932BB5EEEC82D25204699943C",
                  "quality":"1080p",
                  "seeds":247,
                  "peers":419,
                  "size":"1.65 GB",
                  "size_bytes":1766838835,
                  "date_uploaded":"2015-06-28 22:55:41",
                  "date_uploaded_unix":1435488941
               }
            ],
            "date_uploaded":"2015-06-28 08:49:06",
            "date_uploaded_unix":1435438146
         },
         {  
            "id":4245,
            "url":"https:\/\/yts.to\/movie\/bigfoot-county-2012",
            "imdb_code":"tt2108605",
            "title":"Bigfoot County",
            "title_long":"Bigfoot County (2012)",
            "slug":"bigfoot-county-2012",
            "year":2012,
            "rating":2.9,
            "runtime":82,
            "genres":[  
               "Horror",
               "Mystery"
            ],
            "language":"English",
            "mpa_rating":"R",
            "background_image":"https:\/\/s.ynet.io\/assets\/images\/movies\/bigfoot_county_2012\/background.jpg",
            "small_cover_image":"https:\/\/s.ynet.io\/assets\/images\/movies\/bigfoot_county_2012\/small-cover.jpg",
            "medium_cover_image":"https:\/\/s.ynet.io\/assets\/images\/movies\/bigfoot_county_2012\/medium-cover.jpg",
            "state":"ok",
            "torrents":[  
               {  
                  "url":"https:\/\/yts.to\/torrent\/download\/25E5FBDAD49BFD067EEB7778EF1CED753E0E608C.torrent",
                  "hash":"25E5FBDAD49BFD067EEB7778EF1CED753E0E608C",
                  "quality":"720p",
                  "seeds":324,
                  "peers":183,
                  "size":"693.01 MB",
                  "size_bytes":726671831,
                  "date_uploaded":"2015-06-27 14:02:07",
                  "date_uploaded_unix":1435370527
               }
            ],
            "date_uploaded":"2015-06-27 14:02:06",
            "date_uploaded_unix":1435370526
         }
      ]
   },
   "@meta":{  
      "server_time":1435498431,
      "server_timezone":"Pacific\/Auckland",
      "api_version":2,
      "execution_time":"12.3 ms"
   }
}

Can not get one item out of Json

tryign to pull the items from this json, it dosent work, any suggestions?

   <pre>{{statistics|json}}</pre>

<div class = "list">
        <a class =" item" 
           ng-repeat="item in statistics ">




         <p class="title"> {{item.token}} </p>  


        </a>
</div>

how to parse json using GSON in android?

can any body parse this json for me using GSON i tried many time but, failed.

{
    "posting_detail": {
        "posting_id": "14",
        "posting_title": "LuLu Last Offer",
        "posting_desc": "dqwewqewe",
        "mobile_number": "2344234234",
        "phone_number": "34234324",
        "address": "fefdsfds",
        "city_name": "Abu Dhabi",
        "created_on": "2015-06-22 14:55:05",
        "normal_price": null,
        "images": [
            {
                "photo_img": "http://xyz/images/posting/IMG_1212121219.jpg"
            },
            {
                "photo_img": "http://xyz/images/posting/IMG_1212121220.jpg"
            }
        ]
    }
}

Thanks in advance

Passing parameter to partial view - Rails 4/postgresql/json

I have a Deal model with a column/attribute called 'deal_info' which is a json column.

It looks like this for example

deal1.deal_info = [ { "modal_id": "4", "text1":"lorem" }, 
          { "modal_id": "6", "video2":"yonak" },
          { "modal_id": "9", "video2":"boom" } ] 
deal2.deal_info = [ { "modal_id": "10", "text1":"lorem" }, 
          { "modal_id": "11", "video2":"yonak" },
          { "modal_id": "11", "image4":"boom" } ]

On my view deal.html.erb, i have:

<%= for deal_nb in 0..@deal.number_of_deals do %>
  <div class="modal fade" id="myInfoModal<%= modal_nb %>" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <!-- render the right modal type -->
    <%= render "layouts/modal_type_partials/mt#{ @deal.deal_info[deal_nb]['modal_id'] }", parameter_i_want_to_pass: deal_nb  %>
  </div>
<% end %>

Above, as you see above, I'd like to pass for each iteration of the loop inside parameter_i_want_to_pass the number of the iteration loop (2nd iteration would be parameter_i_want_to_pass= 2 for example).

On the partial I have:

<div class="modal-dialog">
  <div class="modal-content">
    <div class="modal-header">
      <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
      <h4 class="modal-title" id="myModalLabel">this is mt4</h4>
    </div>
    <div class="modal-body">
      this is the text: <%= @deal.deal_info[parameter_i_want_to_pass]['text1'] %> 

    </div>
  </div>

I get the following error:

no implicit conversion of String into Integer (on line "this is the text: <%= @deal.deal_info[parameter_i_want_to_pass]")

Actually I even tried to detect more easily the bug by just passing a set number instead of the variable 'deal_nb'

<%= render "layouts/modal_type_partials/mt#{ @deal.deal_info[deal_nb]['modal_id'] }", parameter_i_want_to_pass: 2  %>

But I still get exactly the same error.

Best way to display JSON (well formatted) in UITextView or UIWebView in iOS

I need to display SJON in my iPhone app. Currently I am getting unformatted JSON - like one big string with no indentation.

What would be the best way to display this?

Thanks,

Safe Dynamic JSON Casts In Swift

I suspect that I am not quite grokking Swift 1.2, and I need to RTFM a bit more.

I'm working on a Swift app that reads JSON data from a URI.

If the JSON data is bad, or nonexistent, no issue. The JSON object never instantiates.

However, if the JSON data is good JSON, but not what I want, the object instantiates, but contains a structure that is not what I'm looking for, I get a runtime error.

I looked at using Swift's "RTTI" (dynamicType), but that always returns "<Swift.AnyObject>", no matter what the data is.

I want the JSON to be a specific format: An array of Dictionaries:

[[String:String]]! JSON: [{"key":"value"},{"key","value"},{"Key":"value"}]

If I feed it a single element:

{"Key":"value"}

The routine I have tries to cast it, and that fails.

I want to test the JSON object to make sure that it has a structure I want before casting.

    if(nil != inData) {
        let rawJSONObject: AnyObject? = NSJSONSerialization.JSONObjectWithData(inData, options: nil, error: nil)
        println("Type:\(rawJSONObject.dynamicType)")
        if(nil != rawJSONObject) {
            // THE LINE BELOW BLOWS UP IF I FEED IT "BAD/GOOD" JSON:
            let jsonObject: [[String:String]]! = rawJSONObject as! [[String:String]]!
            // I NEED TO TEST IT BEFORE DOING THE CAST
            if((nil != jsonObject) && (0 < jsonObject.count)) {
                let jsonDictionary: [String:String] = jsonObject[0]
                if("1" == jsonDictionary["semanticAdmin"]) { // We have to have the semantic admin flag set.
                    let testString: String!  = jsonDictionary["versionInt"]

                    if(nil != testString) {
                        let version = testString.toInt()

                        if(version >= self.s_minServerVersion) {    // Has to be a valid version for us to pay attention.
                            self.serverVersionAsInt = version!
                        }
                    }
                }
            }
        }
    }

My question is, is there a good way to test an NSJSONSerialization response for the structure of the JSON before uwinding/casting it?

I feel as if this question may be closer to what I need, but I am having trouble "casting" it to my current issue.

JSON Parsing in Ruby

I'm trying to parse the below from JSON (using the JSON gem) in Ruby:

"daily":{"summary":"Light rain today through Saturday, with temperatures rising to 88°F on Saturday.","icon":"rain","data":[{"time":1435464000,"precipProbability":0.99}]}

Currently what I have is this: forecast["daily"]["data"], but I want to get the precipProbability for time "1435464000". Any suggestion on how to complete my current JSON parsing "query"?

How do I write a json file in a specific format?

I'm nearly done with my program, it loads perfect but one issue I'm having is when I edit the json file through my program, I cannot reload the json file because when I save the file, the formatting becomes different.

So my question is how do I format the json file the same as I'm reading it?

Here's my method for writting a new json file.

    public static boolean write(File npcDefFile) {
    try {
        FileWriter writer = new FileWriter(npcDefFile);
        Throwable localThrowable3 = null;
        try {
            Gson gson = new Gson();
            String json = gson.toJson(NPCDefinitions.getNPCDefinitions());
            writer.write(json);
            writer.flush();
        } catch (Throwable localThrowable1) {
            localThrowable3 = localThrowable1;
            throw localThrowable1;
        } finally {
            if (writer != null) {
                if (localThrowable3 != null) {
                    try {
                        writer.close();
                    } catch (Throwable localThrowable2) {
                        localThrowable3.addSuppressed(localThrowable2);
                    }
                } else {
                    writer.close();
                }
            }
        }
    } catch (NullPointerException | IOException e) {
        System.out.println(e.getLocalizedMessage());
        return false;
    }
    return true;
}

Here's the correct format (3 Space Tab)

    [
  {
    "id": 0,
    "name": "Hans",
    "examine": "Servant of the Duke of Lumbridge.",
    "combat": 0,
    "size": 1,
    "attackable": false,
    "aggressive": false,
    "retreats": false,
    "poisonous": false,
    "respawn": 10,
    "maxHit": 0,
    "hitpoints": 0,
    "attackSpeed": 7,
    "attackAnim": 0,
    "defenceAnim": 0,
    "deathAnim": 0,
    "attackBonus": 0,
    "defenceMelee": 0,
    "defenceRange": 0,
    "defenceMage": 0
  },
  {
    "id": 1,
    "name": "Man",
    "examine": "One of Wildy's many citizens.",
    "combat": 2,
    "size": 1,
    "attackable": true,
    "aggressive": false,
    "retreats": true,
    "poisonous": false,
    "respawn": 10,
    "maxHit": 1,
    "hitpoints": 7,
    "attackSpeed": 7,
    "attackAnim": 422,
    "defenceAnim": 1834,
    "deathAnim": 836,
    "attackBonus": 9,
    "defenceMelee": 9,
    "defenceRange": 9,
    "defenceMage": 0
  }
]

Here's the format after I save the file to a new json file. (Compact)

[{"id":0,"name":"Hans","examine":"Servant of the Duke of               Lumbridge.","combat":0,"size":1,"attackable":false,"aggressive":false,"retreats":false,"poisonous":false,"respawn":10,"maxhit":0,"hp":0,"attackspeed":7,"attackanim":0,"defenceanim":0,"deathanim":0,"attackbonus":0,"defencemelee":0,"defencerange":0,"defencemage":0},{"id":1,"name":"Man","examine":"One of Wildy\u0027s many citizens.","combat":2,"size":1,"attackable":true,"aggressive":false,"retreats":true,"poisonous":false,"respawn":10,"maxhit":1,"hp":7,"attackspeed":7,"attackanim":422,"defenceanim":1834,"deathanim":836,"attackbonus":9,"defencemelee":9,"defencerange":9,"defencemage":0}]

This is how I'm loading the json file.

    /**
 * A dynamic method that allows the user to read and modify the parsed data.
 *
 * @param reader
 *            the reader for retrieving the parsed data.
 * @param builder
 *            the builder for retrieving the parsed data.
 */
public abstract void load(JsonObject reader, Gson builder);

/**
 * Loads the parsed data. How the data is loaded is defined by
 * {@link JsonLoader#load(JsonObject, Gson)}.
 *
 * @return the loader instance, for chaining.
 */
public final JsonLoader load() {
    try (FileReader in = new FileReader(Paths.get(path).toFile())) {
        JsonParser parser = new JsonParser();
        JsonArray array = (JsonArray) parser.parse(in);
        Gson builder = new GsonBuilder().create();

        for (int i = 0; i < array.size(); i++) {
            JsonObject reader = (JsonObject) array.get(i);
            load(reader, builder);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return this;
}

Any help would be appreciated.

EDIT:

Here's an exception that was caught.

java.lang.NullPointerException
at NpcDefinitionLoader.load(NpcDefinitionLoader.java:28)
at JsonLoader.load(JsonLoader.java:56)
at NPCDefinitions.loadNPCDefinitions(NPCDefinitions.java:76)
at DefinitionEditor.loadFile(DefinitionEditor.java:171)
at DefinitionEditor.loadButtonActionPerformed(DefinitionEditor.java:790)
at DefinitionEditor.actionPerformed(DefinitionEditor.java:827)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.AbstractButton.doClick(Unknown Source)
at javax.swing.plaf.basic.BasicMenuItemUI.doClick(Unknown Source)
at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased

Here's the first line the error occured.

int maxHit = reader.get("maxHit").getAsInt();

Second line error

load(reader, builder);

How to i parse this json? [duplicate]

This question already has an answer here:

    String jsondata="{\"studentResult\":[{\"sem1\" :[{\"subname\":\"TOC\",\"subcode\":\"1009\",\"subcredit\":\"6\",\"subgrade\":\"AB\"},
    {\"subname\":\"DS\",\"subcode\":\"10090\",\"subcredit\":\"5\",\"subgrade\":\"BB\"},
    {\"subname\":\"TOC\",\"subcode\":\"1009\",\"subcredit\":\"6\",\"subgrade\":\"AB\"}]},{\"sem2\":
   [{\"subname\":\"AAS\",\"subcode\":\"111009\",\"subcredit\":\"6\",\"subgrade\":\"AB\"},
{\"subname\":\"AE\",\"subcode\":\"103309\",\"subcredit\":\"6\",\"subgrade\":\"DD\"}] }]}";

Unable to parse single json object

I am trying to parse json but unable to get parse result.Always get null.Below is my whole json with single object.

{
    "posting_detail": {
        "posting_id": "14",
        "posting_title": "LuLu Last Offer",
        "posting_desc": "dqwewqewe",
        "mobile_number": "2344234234",
        "phone_number": "34234324",
        "address": "fefdsfds",
        "city_name": "Abu Dhabi",
        "created_on": "2015-06-22 14:55:05",
        "normal_price": null,
        "images": [
            {
                "photo_img": "xyz/images/posting/IMG_1212121219.jpg"
            },
            {
                "photo_img": "xyzm/images/posting/IMG_1212121220.jpg"
            }
        ]
    }
}

And here is the data set class.

package com.iptikarpromotion.vo;

import java.io.Serializable;
import java.util.ArrayList;

import com.google.gson.annotations.SerializedName;

public class PostingDetailVO implements Serializable {

    @SerializedName("posting_id")
    private String posting_id;
    @SerializedName("posting_title")
    private String posting_title;
    @SerializedName("posting_desc")
    private String posting_desc;
    @SerializedName("mobile_number")
    private String mobile_number;
    @SerializedName("phone_number")
    private String phone_number;
    @SerializedName("address")
    private String address;
    @SerializedName("city_name")
    private String city_name;
    @SerializedName("created_on")
    private String created_on;
    @SerializedName("normal_price")
    private String normal_price;
    @SerializedName("images")
    private ArrayList<ImagesVO> images;


    public PostingDetailVO() {
        // TODO Auto-generated constructor stub
    }

    public PostingDetailVO(String posting_id, String posting_title, String posting_desc, String mobile_number, String phone_number, String address, String city_name, String created_on) {

        this.posting_id = posting_id;
        this.posting_title = posting_title;
        this.posting_desc = posting_desc;
        this.mobile_number = mobile_number;
        this.phone_number = phone_number;
        this.address = address;
        this.city_name = city_name;
        this.created_on = created_on;

    }

    public String getPosting_id() {
        return posting_id;
    }

    public void setPosting_id(String posting_id) {
        this.posting_id = posting_id;
    }

    public String getPosting_title() {
        return posting_title;
    }

    public void setPosting_title(String posting_title) {
        this.posting_title = posting_title;
    }

    public String getPosting_desc() {
        return posting_desc;
    }

    public void setPosting_desc(String posting_desc) {
        this.posting_desc = posting_desc;
    }

    public String getMobile_number() {
        return mobile_number;
    }

    public void setMobile_number(String mobile_number) {
        this.mobile_number = mobile_number;
    }

    public String getPhone_number() {
        return phone_number;
    }

    public void setPhone_number(String phone_number) {
        this.phone_number = phone_number;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getCity_name() {
        return city_name;
    }

    public void setCity_name(String city_name) {
        this.city_name = city_name;
    }

    public String getCreated_on() {
        return created_on;
    }

    public void setCreated_on(String created_on) {
        this.created_on = created_on;
    }

    public String getNormal_price() {
        return normal_price;
    }

    public void setNormal_price(String normal_price) {
        this.normal_price = normal_price;
    }

    public ArrayList<ImagesVO> getImages() {
        return images;
    }

    public void setImages(ArrayList<ImagesVO> images) {
        this.images = images;
    }

}

Other images data set class

public class ImagesVO implements Serializable {

    @SerializedName("photo_img")
    private String photo_img;

    public String getPhoto_img() {
        return photo_img;
    }

    public void setPhoto_img(String photo_img) {
        this.photo_img = photo_img;
    }
}

And here is the parser method. Nothing wrong with the response. but only problem is unable to parse the whole json.

 public static PostingDetailVO getPostingDetail(String response){

      PostingDetailVO postingDetailVO = new PostingDetailVO();

      if (response !=null) {

          try {
            JSONObject jsonObject = new JSONObject(response);

            if (jsonObject !=null && jsonObject.has(KEY_POSTING_DETAIL)) {

                GsonBuilder builder = new GsonBuilder();

                Gson gson = builder.create();

                postingDetailVO = gson.fromJson(jsonObject.toString(), PostingDetailVO.class);

                Log.e("", "WORKING BOY==" + postingDetailVO.getPhone_number());

               }

            } catch (JSONException e) {

                e.printStackTrace();
            }
        }

        return postingDetailVO;

    }


}

Relationship between Fetching a Collection and Parsing its Associated Model

When one calls fetch() on a BackboneJS collection, why and how does parse() in the model also get called? I basically have Board collection and model, and also List collection and model. A List belongs-to a Board. I want to send the List down as JSON data with a Board model (when a "GET" request is called, for instance); however, I do NOT want to send the List down as JSON data when the collection is fetched.

My understanding was that calling fetch on a collection goes through the following steps (never going through the model, let alone the parse() on the model):

index action in controller -> sends JSON/data to Backbone -> the collection receives this data and stores it

I have a collection of boards in that has an associated model:

Board Collection:

TrelloClone.Collections.Boards = Backbone.Collection.extend({
  url: '/api/boards',

  model: TrelloClone.Models.Board
});

TrelloClone.Collections.boards = new TrelloClone.Collections.Boards();

Board Model:

TrelloClone.Models.Board = Backbone.Model.extend({
  urlRoot: '/api/boards',

  lists: function() {
    if(!this._lists) {
        this._lists = new TrelloClone.Collections.Lists([], {board: this});
    }
    return this._lists;
  },

  parse: function(response) {
    console.log("parsing");
    if(response.lists) {
        console.log("inside lists");
        this.lists().set(response.lists);
        delete response.lists;
    }
  }
});

Essentially, for a particular Board model, I send back "lists" with that board:

#in the boards controller
def show
  @board = Board.includes(:members, lists: :cards).find(params[:id])

  if @board.is_member?(current_user)
    render :show
  else
    render json: ["You aren't a member of this board"], status: 403
  end
end

...

#in the JBuilder file...
json.extract! @board, :title

json.lists @board.lists do |list|
    json.extract! list, :title, :ord 

    json.cards list.cards do |card|
        json.extract! card, :title, :done
    end
end

For a Board collection, on the other hand, I do not send back the "list":

def index
  @boards = current_user.boards
  render json: @boards
end

The problem with my above implementation is that when I fetch() the Board collection, the attributes of each Board object are not sent over. But when I comment out the parse() function, everything works fine.

EDIT: I figured out why I wasn't getting data on a collection fetch. I forgot to return response at the end of the parse function. It'd be nice if someone could clarify what exactly are the sequence of steps that occur when a collection is fetched (where the parsing happens in this sequence). Thanks!

Layout not displayed with post.content in Jekyll

When I build, Jekyll only display the post content without the layout. That is, it only inject the raw md/html post content and disregard completely the layout I attached to the article

here is my index.html

    ---
    layout: default
    ---

    {% for post in site.posts reversed %}
        {{ post.content }}
    {% endfor %}

my post layout

---
layout: none
---

    <div class="container">
        <div class="row first-row">
            <div class="col-sm-12">
                <div class="title-area">
                    <h2>{{ page.title }}</h2>
                    <p>{{ page.subtitle }}</p>
                </div>
                <div class="text-area">
                    {{ content }}
                </div>
            </div>
        </div>
    </div>

my post

---
layout: post
title: "test"
subtitle: "subtitle test"
---

Lorem ipsum

malformed JSON string Error while passing JSON from AngularJS

I am trying to pass JSON string in ajax request. This is my code.

    NewOrder =  JSON.stringify (NewOrder);
    alert (NewOrder);

    var req = {
        url: '/cgi-bin/PlaceOrder.pl',
        method: 'POST',
        headers: { 'Content-Type': 'application/json'},
        data: "mydata="+ NewOrder
    };  

    $http(req)
    .success(function (data, status, headers, config) {
        alert ('success');
    })
    .error(function (data, status, headers, config) {
        alert (status);
        alert (data);
        alert ('Error')
    });

alert (NewOrder) gives -

{"ItemList":[{"ItemName":"Quality Plus Pure Besan 500 GM","Quantity":1,"MRP":"28.00","SellPrice":"25.00"}],"CustomerID":1,"DeliverySlot":2,"PaymentMode":1}

Which seems to be a valid JSON string.

But in script side I am getting following error. in this line

my $decdata = decode_json($cgi->param('mydata'));

malformed JSON string, neither array, object, number, string or atom, at character offset 0 (before "(end of string)")

Can please someone help me why i am getting this error?

Cannot resolved OWM_Date - OWM JAPIs in Android Studio

I’m working on Udacity Sunshine Project Lesson 2 and I realised android.text.format.Time is now deprecated. To fix the problem I imported a Java library called OWM JAPIs 2.5.0.5.zip.

I then removed the following bits of code:

  Time dayTime = new Time();
    dayTime.setToNow();
    int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff);
    dayTime = new Time();

and instead put the following in the for loop:

long dateTime = dayForecast.getLong(OWM_DATE);
dateTime *= 1000L;
day = getReadableDateString(dateTime);

The original code gets the date from the phone, whereas my code gets it from the JSON file.

Everything else works fine except I’m getting a “cannot resolve symbol OWM_DATE” as shown in this screenshot:

enter image description here

I tried to add it again but it looks like OWM_DATE is not even available in the drop down menu as shown in the screenshot below: enter image description here

Can you please advise how to fix this? Any help would be greatly appreciated.

Here’s my code

package com.andm.bcg.sunshine;

....

import java.text.SimpleDateFormat;

import net.aksingh.owmjapis.AbstractWeather;
import net.aksingh.owmjapis.CurrentWeather;
import net.aksingh.owmjapis.DailyForecast;
import net.aksingh.owmjapis.HourlyForecast;
import net.aksingh.owmjapis.OpenWeatherMap;
import net.aksingh.owmjapis.Tools;
import net.aksingh.owmjapis.AbstractForecast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;






public class ForecastFragment extends Fragment {

   private ArrayAdapter<String> mForecastAdapter;

   public ForecastFragment() {
   }


   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       // Add this line in order for this fragment to handle menu events.
       setHasOptionsMenu(true);
   }

   @Override
   public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
       inflater.inflate(R.menu.forecastfragment, menu);
   }

   @Override
   public boolean onOptionsItemSelected(MenuItem item) {
       // Handle action bar item clicks here. The action bar will
       // automatically handle clicks on the Home/Up button, so long
       // as you specify a parent activity in AndroidManifest.xml.
       int id = item.getItemId();
       if (id == R.id.action_refresh) {
           FetchWeatherTask weatherTask = new FetchWeatherTask();
           weatherTask.execute("94043");
           return true;
       }
       return super.onOptionsItemSelected(item);
   }


   @Override
   public View onCreateView(LayoutInflater inflater, ViewGroup container,
                            Bundle savedInstanceState) {

       String[] data = {
               "Mon 6/23 - Sunny - 31/17",
               "Tue 6/24 - Foggy - 21/8",
               "Wed 6/25 - Cloudy - 22/17",
               "Thurs 6/26 - Rainy - 18/11",
               "Fri 6/27 - Foggy - 21/10",
               "Sat 6/28 - TRAPPED IN WEATHERSTATION - 23/18",
               "Sun 6/29 - Sunny - 20/7"
       };
       List<String> weekForecast = new ArrayList<String>(Arrays.asList(data));

       mForecastAdapter =
               new ArrayAdapter<String>(
                       getActivity(),
                       R.layout.list_item_forecast,
                       R.id.list_item_forecast_texview,
                       weekForecast);

       View rootView = inflater.inflate(R.layout.fragment_main, container, false);

       ListView listView = (ListView) rootView.findViewById(R.id.listview_forecast);
       listView.setAdapter(mForecastAdapter);


       return rootView;

   }


   public class FetchWeatherTask extends AsyncTask<String, Void, String[]> {

       private final String LOG_TAG = FetchWeatherTask.class.getSimpleName();

       /* The date/time conversion code is going to be moved outside the asynctask later,
        * so for convenience we're breaking it out into its own method now.
        */
       private String getReadableDateString(long time){
           // Because the API returns a unix timestamp (measured in seconds),
           // it must be converted to milliseconds in order to be converted to valid date.
           SimpleDateFormat shortenedDateFormat = new SimpleDateFormat("EEE MMM dd");
           return shortenedDateFormat.format(time);
       }

       /**
        * Prepare the weather high/lows for presentation.
        */
       private String formatHighLows(double high, double low) {
           // For presentation, assume the user doesn't care about tenths of a degree.
           long roundedHigh = Math.round(high);
           long roundedLow = Math.round(low);

           String highLowStr = roundedHigh + "/" + roundedLow;
           return highLowStr;
       }

       /**
        * Take the String representing the complete forecast in JSON Format and
        * pull out the data we need to construct the Strings needed for the wireframes.
        *
        * Fortunately parsing is easy:  constructor takes the JSON string and converts it
        * into an Object hierarchy for us.
        */
       private String[] getWeatherDataFromJson(String forecastJsonStr, int numDays)
               throws JSONException {

           // These are the names of the JSON objects that need to be extracted.
           final String OWM_LIST = "list";
           final String OWM_WEATHER = "weather";
           final String OWM_TEMPERATURE = "temp";
           final String OWM_MAX = "max";
           final String OWM_MIN = "min";
           final String OWM_DESCRIPTION = "main";

           JSONObject forecastJson = new JSONObject(forecastJsonStr);
           JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);

           // OWM returns daily forecasts based upon the local time of the city that is being
           // asked for, which means that we need to know the GMT offset to translate this data
           // properly.

           // Since this data is also sent in-order and the first day is always the
           // current day, we're going to take advantage of that to get a nice
           // normalized UTC date for all of our weather.




           String[] resultStrs = new String[numDays];
           for(int i = 0; i < weatherArray.length(); i++) {
               // For now, using the format "Day, description, hi/low"
               String day;
               String description;
               String highAndLow;





               // Get the JSON object representing the day
               JSONObject dayForecast = weatherArray.getJSONObject(i);

               // The date/time is returned as a long.  We need to convert that
               // into something human-readable, since most people won't read "1400356800" as
               // "this saturday".
               long dateTime = dayForecast.getLong(OWM_DATE);
               // Cheating to convert this to UTC time, which is what we want anyhow
               dateTime *= 1000L;
               day = getReadableDateString(dateTime);

               // description is in a child array called "weather", which is 1 element long.
               JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
               description = weatherObject.getString(OWM_DESCRIPTION);

               // Temperatures are in a child object called "temp".  Try not to name variables
               // "temp" when working with temperature.  It confuses everybody.
               JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
               double high = temperatureObject.getDouble(OWM_MAX);
               double low = temperatureObject.getDouble(OWM_MIN);

               highAndLow = formatHighLows(high, low);
               resultStrs[i] = day + " - " + description + " - " + highAndLow;
           }

           for (String s : resultStrs) {
               Log.v(LOG_TAG, "Forecast entry: " + s);
           }
           return resultStrs;

       }



       @Override
       protected String[] doInBackground(String... params) {

           // If there's no zip code, there's nothing to look up.  Verify size of params.
           if (params.length == 0) {
               return null;
           }


           HttpURLConnection urlConnection = null;
           BufferedReader reader = null;

           // Will contain the raw JSON response as a string.
           String forecastJsonStr = null;

           String format = "json";
           String units = "metric";
           int numDays = 7;

           try {
               // Construct the URL for the OpenWeatherMap query
               // Possible parameters are avaiable at OWM's forecast API page, at
               // http://ift.tt/1pg3I3j
               final String FORECAST_BASE_URL =
                       "http://ift.tt/1jqKpkt?";
               final String QUERY_PARAM = "q";
               final String FORMAT_PARAM = "mode";
               final String UNITS_PARAM = "units";
               final String DAYS_PARAM = "cnt";

               Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon()
                       .appendQueryParameter(QUERY_PARAM, params[0])
                       .appendQueryParameter(FORMAT_PARAM, format)
                       .appendQueryParameter(UNITS_PARAM, units)
                       .appendQueryParameter(DAYS_PARAM, Integer.toString(numDays))
                       .build();

               URL url = new URL(builtUri.toString());

               Log.v(LOG_TAG, "Built URI " + builtUri.toString());


               urlConnection = (HttpURLConnection) url.openConnection();
               urlConnection.setRequestMethod("GET");
               urlConnection.connect();


               InputStream inputStream = urlConnection.getInputStream();
               StringBuffer buffer = new StringBuffer();
               if (inputStream == null) {

                   return null;
               }
               reader = new BufferedReader(new InputStreamReader(inputStream));

               String line;
               while ((line = reader.readLine()) != null) {

                   buffer.append(line + "\n");
               }

               if (buffer.length() == 0) {

                   return null;
               }
               forecastJsonStr = buffer.toString();
           } catch (IOException e) {
               Log.e(LOG_TAG, "Error ", e);

               return null;
           } finally {
               if (urlConnection != null) {
                   urlConnection.disconnect();
               }
               if (reader != null) {
                   try {
                       reader.close();
                   } catch (final IOException e) {
                       Log.e(LOG_TAG, "Error closing stream", e);
                   }
               }
           }
           return null;
       }
       @Override
       protected void onPostExecute(String[] result) {
           if (result != null) {
               mForecastAdapter.clear();
               for(String dayForecastStr : result) {
                   mForecastAdapter.add(dayForecastStr);
               }
               // New data is back from the server.  Hooray!

           }
       }
   }
}

How to make ExpandableListView with JSON data in Android

In my app I want to make a ExpandableListView parsing JSON data. Here is my JSON data.

 [  
   {  
      "UserId":"raj",
      "PrvCusID":"10000000",
      "ItemName":"popcorn",
      "RPU":75.0000,
      "VAT":0.0000,
      "QTY":1,
      "CustomerName":"Rakib Hossain"
   },
   {  
      "UserId":"raj",
      "PrvCusID":"10000001",
      "ItemName":"chips",
      "RPU":50.0000,
      "VAT":0.0000,
      "QTY":1,
      "CustomerName":"Sehav"
   }
]

Here "CustomerName" will be group name and "ItemName", "RPU", "QTY" will be in child. For a customer there will be many items, and have to show total "RPU" for each customer. How can I do this. Thanks in advance.

Google chart local json file loading issue

I am new to google chart. I tried to load a json data file but somehow my script does not recognize it. First, I got this code, which works fine.

<!DOCTYPE html>
<html>
  <head>
    <!-- EXTERNAL LIBS-->
    <script src="http://ift.tt/1qRgvOJ"></script>
    <script src="http://ift.tt/JuZcy0"></script>

    <!-- EXAMPLE SCRIPT -->
    <script>

      // onload callback
      function drawChart() {

        var public_key = 'dZ4EVmE8yGCRGx5XRX1W';

        // JSONP request
        var jsonData = $.ajax({
          url: 'http://ift.tt/XQ3ZTg' + public_key + '.json',
          //This json local file is in the same directory of this html file. It was downloaded from the sparkfun.
          //url: 'stream_dZ4EVmE8yGCRGx5XRX1W.json'
          data: {page: 1},
          dataType: 'json',
        }).done(function (results) {
          var data = new google.visualization.DataTable();
          console.log(data);
          data.addColumn('datetime', 'Time');
          data.addColumn('number', 'Temp');

          $.each(results, function (i, row) {
            data.addRow([
              (new Date(row.timestamp)),
               parseFloat(row.tempf),
            ]);
          });
          var chart = new google.visualization.LineChart($('#chart').get(0));

          chart.draw(data, {
            title: 'Wimp Weather Station'
          });

        });

      }

      // load chart lib
      google.load('visualization', '1', {
        packages: ['corechart']
      });

      // call drawChart once google charts is loaded
      google.setOnLoadCallback(drawChart);

    </script>

  </head>
  <body>
    <div id="chart" style="width: 100%;"></div>
  </body>
</html>

But, if I uncomment the line "url:stream-...." and comment the line "url:'https://data...", the script somehow does not work. It must be the same json file but depending on "url", the code does not work. I don't know how to resolve this. Thank you.

JSON.parse(json_string_from_php) produces weird array

I'm having a bit of difficulty with transferring a JSON object from the server to the client-side javascript

I have a rows of data fetched from MySQL query stored into $result

Here's the code:

    var json = '<?= json_encode($result->fetch_all()) ?>';
    var word_list = JSON.parse(json);
    console.log(word_list);     //index.php:23
    console.log(json);          //index.php:24

This is the result in chrome console: number of arrays in the concise version and expanded version don't match

Can someone tell me:
1. Why line 23 shows length of 5 when folded, then only show length of 4 when unfolded?
2. Where did word5 go? FYI, the word that disappears changes every time I refresh.

Java entity classes from my proprietary database?

Friends i have one database which maintain schema files in JSON format but it doesn't support JDBC connectivity so i can't use existing netbeans feature "entity class from database" this proprietary database gives me following table schema

{
"uid":{
  "auto-define":"none",
  "name":"uid",
  "index":"unique",
  "type":{
     "length":-1,
     "type":"STRING"
  }
},
"createdAt":{
  "auto-define":"none",
  "name":"createdAt",
  "index":"none",
  "type":{
     "type":"LONG"
  }
},
"lastLogin":{
  "auto-define":"none",
  "name":"lastLogin",
  "index":"none",
  "type":{
     "type":"LONG"
  }
},
"password":{
  "auto-define":"none",
  "name":"password",
  "index":"none",
  "type":{
     "length":-1,
     "type":"STRING"
  }
},
"blocked":{
  "auto-define":"none",
  "name":"blocked",
  "index":"none",
  "type":{
     "type":"BOOLEAN"
  }
},
"replication-type":"distributed",
"replication-factor":1,
"email":{
  "auto-define":"none",
  "name":"email",
  "index":"btree",
  "type":{
     "length":-1,
     "type":"STRING"
  }
},
"primary":"uid",
"network":{
  "auto-define":"none",
  "name":"network",
  "index":"none",
  "type":{
     "length":-1,
     "type":"STRING"
  }
 }
}

so from above schema (JSON) i want the entity class like

@Entity
public class User extends CloudStorage {
@Primary
private String id;
private String name;
private String email;

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}
}

please help me, i want to develop a NetBeans plugin which will get all the table schema (JSON) and gives the ability to select the table and generate entity classes.

PHP prematurely exiting while loop

Pretty new to PHP and I am stuck on a (what I consider) a strange issue. I have spliced this file together, (it was split across several different functions) for testing, and to make it easier to explain the issue.

This is a basic while loop in Laravel and it seems to be exiting prematurely but oddly not exiting out to the line AFTER the loop, but exiting out BEFORE the loop and then entering again. Can't for the life of me workout why. I have added some log events throughout the function so I could try understand what was happening.

This is correctly fetching and writting products to the DB up until page 7 and then I get a "Start API Helper" event on log but never get an "End API helper". So somewhere in page 7 something is causing the while loop to exit out to the lines above, reset the pagecount to 0. then re-enter the loop, fetching the first lot of products and throwing an SQL duplicate key exception when writing. I know it is exiting out to before the loop as I get a "Before while", right after "New Client" in the log. And of course, the pagecount is resetting. How can this happen?

Any help would be sooooo greatly appreciated. Sorry the formatting of the PHP got a bit lost in translation.

public function store()
{

    $items = array();

    Log::info('Before while');

    $pagecount = 0;
    $prodcount = 1;

     while ($prodcount > 0) {

        Log::info('Top of while');

        $prodcount = 0; // Reset product counter

        Log::info('Page Count:'.$pagecount);

        Log::info('Start API Helper');

    $headers = array(
        'NETOAPI_KEY' => env('NETO_API_KEY'),
        'Content-Type' => 'application/json',
        'Accept' => 'application/json',
        'NETOAPI_ACTION' => 'GetItem'
    );

    Log::info('Headers Declared');

    $body = '{
        "Filter": {
            "DateAddedFrom" : "2013-06-01 12:00:00",
            "Page": "'.$pagecount.'",
            "Limit": "500",
            "OutputSelector": [
                **Lots of JSON here - removed for readability**
            ]
        }
    }'; 

Log::info('Start API Helper');

    $client = new client();
    Log::info('New Client');

    try {
       $res = $client->post(env('NETO_API_URL'), [ 'headers' => $headers , 'body' => $body ]);
    } catch (RequestException $e) {
        echo $e->getRequest();
        Log::error($e->getRequest());
        if ($e->hasResponse()) {
            echo $e->getResponse();
            Log::error($e->getResponse());
        }
    }

    Log::info('End API Helper');
    $items = json_decode(utf8_encode($res->getBody()), true);

        foreach($items["Item"] as $item)
        {

            // JSON is returning an empty array for empty strings. Need to convert to empty string for SQL save.
            foreach($item as $key => $value){
                if (empty($value)) {
                     $item["$key"] = "";
                }
            }

            $Product = new Item;
            $Product->SKU = array_get($item, 'SKU');
            ** LOTS OF DB FIELDS REMOVED FROM HERE FOR READABILITY**
            $Product->save();
            $prodcount++;               
        } 

        $pagecount++;
        Log::info($prodcount.' products written to DB:');
        Log::info('Bottom of while'); 
    };

    Log::info('Exited While'); 

    return 'Complete';

}

jquery is this a valid http request

I have this http request

GET /deals/couchbaseDocument/_search
{
    "query" : {
        "match" : {
            "amenities" : "Maids "
        }
    }
}

when i put it in curl, it gives me results, i want to build a web app to call that request.

what i did is removing the newlines and put the whole text in .getjson()

as this:

var query = $("#query").val();
        query = query.replace(/(\r\n|\n|\r)/gm,"");
        $.getJSON(query, function (results) {
            alert("success");
            alert(results);
        })
        .success(function () { alert(" second success"); })
        .error(function () {
            alert("error");
            alert(query);
        });

i kept getting the error alert, i wonder if what i did is actually what should it be done to send that request

I read this

I found that .getJson could be like this:

$.getJSON('httpURL',
       { parameter1: "parameter value", parameter2: "parameter value" })

i wonder if i should pass my json request as a parameter

in case of the whole picture** i am working on sense elasticsearch plugin

How to schedule data sync in PhoneGap app, retrieving JSON

I am building a PhoneGap app, and currently have setup some datasources that have a JSON feed I pull from, to populate my app with data. Right now, it only pulls that data once, the first time the app is run.

I would like to download data everytime the app first opens, and then if it stays open for longer than 15 minutes, it updates again. The json feed can be queried with a last_mod_day in the URL so it pulls only the data that has changed.

What would be recommended to go about this, and how to check for a WiFi/Data Connection on the phone, and if not it fails quietly?

Below is the code for my current function to grab the feed.

function downloadFileError(evt) {
console.log('downloadFileError: ');
console.log(evt.target.error);
}

function downloadFile(ep) {
window.requestFileSystem(
    LocalFileSystem.PERSISTENT, 
    0, 
    function onFileSystemSuccess(fileSystem) {
        fileSystem.root.getFile("dummy.json", {
            create: true,
            exclusive: false
        }, 
        function gotFileEntry(fileEntry) {
            var filename = cordova.file.dataDirectory + 'assets/json/' + ep + '.json';
            var fileTransfer = new FileTransfer();
            fileEntry.remove();
            console.log('looking at ' + filename);
            fileTransfer.download(
                encodeURI("http://ift.tt/1GTLmzu" + ep), 
                filename,
                    function(theFile) {
                        console.log("download complete: " + theFile.toURL());
                    }, 
                    function(error) {
                        console.log("DLERR: src=" + error.source + " t=" + error.target);
                    }
            );
        }, 
        function(evt) {
            console.log(evt);
            console.log('fn: ' + filename);
        }
        );
    }, 
downloadFileError);
}

function downloadDynamicPages() {

var deferred = $.Deferred();

var pages = ['setOne','setTwo','setThree','setFour','setFive','setSix'];
var cnt = 0;
var total_pages = pages.length; 

//checkConnection();

$.each(pages,function(k,v) {

    console.log('looking at ' + v);
    downloadFile(v);
    cnt++;
    if(cnt >= total_pages) {
        deferred.resolve('all done with files');
    }
});


return deferred.promise();

}

Any help on any part of these questions would help me greatly. If needed, I can answer any questions. Thank you Stack.

the method JsonConvert.DeserializeObject converts id's into zero

I've got a string:

string model = "{\"Game\":{\"GameId\":1,\"Board\":[0,0,0,0,0,0,0,0,0],\"User1Id\":1,\"User2Id\":2,\"UserIdTurn\":1,\"WinnerId\":0,\"IsGameOver\":false},\"User\":{\"UserId\":1,\"UserName\":\"a\",\"Password\":\"a\",\"Password2\":\"a\",\"Games\":[]}}" 

And when I use this code:

GameModel myModel = JsonConvert.DeserializeObject<GameModel>(model);

It works pretty good but with only one problem - it changes my Game and User id's into zero. why does it happen and how can I solve it? I write in c# by the way.

those are my classes :

        public class GameModel
    {

        public Game Game { get; set; }

        public User User { get; set; }

    }

public class Game
    {

        public Game()
        {
            Board = new SquareState[9];                     
        }

        public Game(int user1Id)
        {
            Board = new SquareState[9];
            User1Id = user1Id;
            UserIdTurn = user1Id;
        }
        public int GameId { get; private set; }

        public SquareState[] Board { get; set; }

        [Required]
        public int User1Id { get; set; }

        public int User2Id { get; set; }

        public int UserIdTurn { get; set; }


        public int WinnerId { get; set; }

        public bool IsGameOver { get; set; }

    }

    public class User
    {
        public User()
        {
            Games = new List<Game>();
        }
        public int UserId { get; private set; }

        [Required]
        [Display(Name = "User Name:")]
        public string UserName { get; set; }


        [Required]
        [DataType(DataType.Password)]
        public string Password { get; set; }

        [Required]
        [Display(Name = "re-enter Password")]
        [DataType(DataType.Password)]
        [Compare("Password", ErrorMessage = "Passwords not match")]
        public string Password2 { get; set; }

        public List<Game> Games { get; set; }
    }

How to handle nested objects in processing a JSON stream

I am working on a program where we need to process very large JSON file, so I would like to use a streaming event oriented reader (like jsonstreamingparser) so that we can avoid loading the entire structure into memory at one time. Something I'm concerned about though is the object structure that seems to be required to make this work. For example, say I'm writing a program like Evite to send out invitations to an activity, with a JSON structure like:

{  
  "title": "U2 Concert",  
  "location": "San Jose",  
  "attendees": [  
    {"email": "foo@bar.com"},  
    {"email": "baz@bar.com"}
  ],  
  "date": "July 4, 2015"  
}

What I would like to do is have a programming "event" that when the stream encounters a new attendee, sends out an invite email. But, I can't do that because the stream has not yet reached the date of the event.
Of course, given the example, it's fine to just read everything into memory - but my dataset has complex objects where the "attendees" attribute are, and there can be tens of thousands of them.

Another "solution" is to just mandate: you HAVE to put all the required "parent" attributes first, but that is what I'm trying to find a way around.

Any ideas?

Is there a tool that can generate call to rest web service

I have a URL to rest web service that I call by passing JSON with all parameters.
But I don't know some parameters names.
Is there some tool where I can enter service URL and method name to get JSON example that I must pass to this method?

I know that tools like this exist for SOAP services but I need for REST.

Returning TWO Lists using JSON and Serializer

I'm sending a List from my ASP.NET WebMethod to my Javascript using this:

List<Person> plist = new List<Person>();

string json = "";
System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
json = oSerializer.Serialize(plist );

return json;

And I'm using this to retrieve these values from my JS:

function onSuccess(val) {
        var obj = JSON.parse(val)
        obj.forEach(function (entry) {
               console.log(entry);
       });
}

Everything works well. However now I want to return TWO lists such as:

List<Person> plist = new List<Person>();
List<Car> carlist = new List<Car>();

using the same mechanism I used before. How can I insert two lists to the Serializer and print them from my JS?

EDIT

How do I get the values from the JS? Is this the way?

obj.forEach(function (entry) {
         entry.forEach(function (act)
         {
               console.log(act);
         })
});

Rails API: make application controller serve JSON

This tutorial from Fancy Pixel says:

Now we need to change the application controller so that it inherits from ActionController::API, and kiss the protect_from_forgery goodbye. Since we are serving only JSON, it makes sense to add

respond_to :json

to the applciation controller, helps DRYing all out. While we are at it, we might as well delete the assets and views folders, we won’t need them.

I am not sure about what I am supposed to do.

This is what my application controller looks like:

class ApplicationController < ActionController::API
    respond_to :json
end

Is it correct?

Also, should I keep or remove protect_from_forgery with: :null_session :

class ApplicationController < ActionController::API
  protect_from_forgery with: :null_session
  respond_to :json
end

Filter values of multiple properties with an array of values

So I really would like to make a duplicate out of my previous failed question because I wasn't really able to explain myself properly and thus didn't get the answer (and haven't really solved my issue).

There is the JSON:

[
  {
    "id": 2,
    "name": "Google",
    "country": "Sweden"
  },
  {
    "id": 3,
    "name": "Google",
    "country": "USA"
  },
  {
    "id": 9,
    "name": "Google",
    "country": "Ukraine"
  },
  {
    "id": 10,
    "name": "Bing",
    "country": "Sweden"
  }
]

What I failed to do previously I guess is to post what I have so far and explain better what I need. This is what I have right now:

 $scope.loadSearchEngines = function ($query) {
     return $http.get('search-engines.json', {cache: true}).then(function (response) {
         var tags = response.data;
         return tags.filter(function (tag) {
             return tag.name.toLowerCase().indexOf($query.toLowerCase()) != -1;
         });
     });
 };

This filter restricts me to search through only the name property, while ideally I would like to search through any property (or well, all the properties, rather) and I'd like the filter to work with an array of parameters so that each word would separately look through each property in the object and find a match.

In the previous post a person posted a for loop for it, but that is exactly the kind of unintuitive thing I want to avoid. I know what I want the result to be but I just can't think of an approach (lodash/underscore seemingly almost does something like this, but I think there is something missing from somewhere or I am really bad at understanding the docs).

Examples:

In case I write "google sweden", it will only show the 1 result, if I write "sweden", it would show the one from google and the one from bing. In case I write "in", it should show "bINg" and google "ukraINe" I guess.

This seemed like a much less of a hassle at first but I can't really wrap my head around this using a filter. I really don't have any ideas to post because they have been embarrassingly bad and this is a really grey area for me.

PHP JSON_encode output

This is my first time using PHP and I am making a script that will output text in JSON format. However I am encountering problems with the formatting.

Can someone explain why my browser renders the following code as..

"1", 'b' => "2", ), array( 'a' => "1", 'b' => "2", 'c' => "3", ) ) ); ?>

instead of something like this?

[ 
  [ { "a" : "1" }, { "b" : "2" } ],
  [ { "a" : "1" }, { "b" : "2" }, { "c" : "3" } ]
]

Code:

<body>
<?php

echo json_encode(
   array( 
      array( 
         'a' => "1", 
         'b' => "2"
      ), 
      array( 
         'a' => "1", 
         'b' => "2", 
         'c' => "3"
      )
   )
);

?>
</body>

Send Data to Server in Android using JSON

I want to send data from android app to remote server. I have tried to send data as a sample to the server but it is working. I am uploading my code below. I am not sure but may be my data sending formate is wrong.

The link need to show a success message. Unfortunately it not showing any change.

public void postData() throws JSONException {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://ift.tt/1dfhGlr");
    JSONObject json = new JSONObject();

    try {
        // JSON data:
        json.put("task_title", "Fahmi Rahman");
        json.put("task_details", "sysdev");

        JSONArray postjson=new JSONArray();
        postjson.put(json);

        // Post the data:
        httppost.setHeader("json",json.toString());
        httppost.getParams().setParameter("jsonpost",postjson);

        // Execute HTTP Post Request
        System.out.print(json);
        HttpResponse response = httpclient.execute(httppost);

        // for JSON:
        if(response != null)
        {
            InputStream is = response.getEntity().getContent();

            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            StringBuilder sb = new StringBuilder();

            String line = null;
            try {
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //text = sb.toString();
        }

        //tv.setText(text);

    }catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }
}

And I need to send data this formate

{"task":{
            "task_title":"All json formate",
            "task_details":"View All task list, View task list by user id, Add new task"}}

Can anyone tell me how it may work?

samedi 27 juin 2015

How do I get ngrams array string and estfrequency as seperate elements in a hive table using HiveQL?

I am analyzing my own tweets and I have inserted the data into the Hive table using Hive JSON SerDE . I want to find out the frequency of all two word phrases in my tweets as a table. The output should look something like:

phrase             frequency
["the","room"]      1248.0
["a","boy"]        1039.0
["rt","to"]        1032.0
["to","ct"]         986.0

Right now, I am able to do it for all single word phrases and I am getting the output as:

phrase     frequency
["the"]     1248.0
["a"]       1039.0
["rt"]      1032.0
["to"]      986.0
["you"]     828.0

For the one word phrase output, my code is:

create table ng(new_ar array<struct<ngram:array<string>,estfrequency:double>>);

insert overwrite table ng select context_ngrams(sentences(lower(text)),array(null),100) as word from tweets;

create table wordFreq (ngram array<string>,  estfrequency double);

INSERT OVERWRITE TABLE wordFreq SELECT X.ngram, X.estfrequency from ng LATERAL VIEW explode(new_ar) Z as X;    

select * from wordFreq;

How do I modify the above code for my desired output?

Submitting File and Json data to webapi from HttpClient

I want to send file and json data from HttpClient to web api server.
I cant seem to access the json in the server via the payload, only as a json var.

 public class RegulationFilesController : BaseApiController
    {
        public void PostFile(RegulationFileDto dto)
        {
            //the dto is null here
        }
    }

here is the client:

   using (var client = new HttpClient())
                {
                    using (var content = new MultipartFormDataContent())
                    {
                        client.BaseAddress = new Uri(ConfigurationManager.AppSettings["ApiHost"]);
                        content.Add(new StreamContent(File.OpenRead(@"C:\\Chair.png")), "Chair", "Chair.png");
                        var parameters = new RegulationFileDto
                        {
                            ExternalAccountId = "1234",
                        };
                        JavaScriptSerializer serializer = new JavaScriptSerializer();
                        content.Add(new StringContent(serializer.Serialize(parameters), Encoding.UTF8, "application/json"));

                            var resTask = client.PostAsync("api/RegulationFiles", content); //?ApiKey=24Option_key
                            resTask.Wait();
                            resTask.ContinueWith(async responseTask =>
                            {
                                var res = await responseTask.Result.Content.ReadAsStringAsync();


                            }
                                );

                    }
                }

this example will work:HttpClient Multipart Form Post in C# but only via the form-data and not payload.

Can you please suggest how to access the file and the submitted json And the file at the same request?

Thanks

Send array from php to js with ajax and json

I am trying to send an array from php (that i have taken from a mysql table to js).Although there a lot of examples out there i can't seem to make any of them work. The code that i have reached so far is:

php_side.php

<!DOCTYPE html>
<html>
<body>

<?php
//$q = intval($_GET['q']);
header("Content-type: text/javascript");

$con = mysqli_connect("localhost","root","","Tileiatriki"); 
if (!$con) {
    die('Could not connect: ' . mysqli_error($con));
}

//mysqli_select_db($con,"users_in_calls");
$sql="SELECT * FROM users_in_calls";
$result = mysqli_query($con,$sql);


/*while($row = mysqli_fetch_array($result)) {
     echo $row['User1_number'];
     echo "<br/>";
     echo $row['User2_number'];
         echo "<br/>";
     echo $row['canvas_channel'];
         echo "<br/>";
}*/
echo json_encode($result);

    mysqli_close($con);
    ?>
    </body>
    </html>  

test_ajax.html

    $(document).ready(function(){
      $.getJSON('php_side.php', function(data) {
        $(data).each(function(key, value) {
            // Will alert 1, 2 and 3
            alert(value);
        });
     });
   });

This is my first app that i use something like this, so please be a little patient. Thank you!

call webservice and show data on listview

send request format {"method":"item_list","parameter":{"category_id":"1"}} i want to pass json on btn_choose_menu click

package com.example.pattipizza;

import android.os.Bundle; import android.view.View;enter code here import android.view.View.OnClickListener; import android.widget.Button;

public class OrderSelect extends MainActivity {

Button btn_choose_menu, btn_send_order;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.varified_activity);
    btn_choose_menu = (Button) findViewById(R.id.button1);

    btn_choose_menu.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub

        }
    });
    btn_send_order.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

        }
    });

}

}

how to store a collection of string as key and json as value in c++

I am trying to store a collection of key-value pair in cpp, where key will be a string, as will the value - in my case, a JSON string representing an object.

Then I need to access this json object using Key1 For Example

Key1 = name1 Value1 = {name:"Anil Gautam","age":25}

Key2 = name2 Value2 = **strong text** = {name:"Sharan Gupta","age":26}

I want to access

{name:"Anil Gautam","age":25} 

when I input "name1". What Can I possible do to store this kind of data in cpp.

AFNetworking get responseObject in failure block

I am GET a json data from server, but the json data has a line break "\n", so i got the error:

Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Unescaped control character around character 2333.) UserInfo=0x7fa054a02ab0 {NSDebugDescription=Unescaped control character around character 2333.}

So i want to find where's the broken json data, escape it first and then parse it. But i can't find where the response data is.

Any help?

Edited:

            if let d = error.userInfo  {
                    println(d)
         println(d[AFNetworkingOperationFailingURLResponseDataErrorKey])
                }

I tried this in failure block, d[AFNetworkingOperationFailingURLResponseDataErrorKey] prints nil

How Get an array by JSon and how i can set this return value to a modal form?

My Ajax code is

$("a#edit").click(function(){
      var id = $(this).closest('tr').attr('id');
        //alert(id);
$.ajax({
        url: 'getdata.php',
        type: "POST",
        dataType:'JSON',
        data: {
            id: id,
        },
        success:function(result){
            alert(result);
        }
      });
    });

My php code is here...

if ($_REQUEST['id'] != "") 
{
     $id=$_REQUEST['id'];
   $sql = "select * from visit_reports WHERE visit_planner_id='$id'";

        $query = sqlsrv_query( $link, $sql);
        while($data = sqlsrv_fetch_array($query,SQLSRV_FETCH_ASSOC))
            {
              print_r($data);
      }  
  }

In firebug the array i get ..

Array
(
[id] => 1.0000
[visit_planner_id] => 230338
[bi_staff_present_name] => BI staff present name
[bi_staff_trial_function] => BI staff trial function
)

Now how i can use this array value into my specific input field of modal form ?

How to JSON stringify a javascript Date and preserve timezone

I have a date object that's created by the user, with the timezone filled in by the browser, like so:

var date = new Date(2011, 05, 07, 04, 0, 0);
> Tue Jun 07 2011 04:00:00 GMT+1000 (E. Australia Standard Time)

When I stringify it, though, the timezone goes bye-bye

JSON.stringify(date);
> "2011-06-06T18:00:00.000Z"

The best way I can get a ISO8601 string while preserving the browser's timezone is by using moment.js and using moment.format(), but of course that won't work if I'm serializing a whole command via something that uses JSON.stringify internally (in this case, AngularJS)

var command = { time: date, contents: 'foo' };
$http.post('/Notes/Add', command);

For completeness, my domain does need both the local time and the offset.

Unable to read JSON in AngularJS $http from URL on local server

I'm working on my first AngularJS app, and for my data I'm trying to read from a page in Drupal website on my local machine. It's running on Apache, and it's accessible from an alias URL (i.e. http://mylocalsite instead of http://localhost/mylocalsite). The page displays nothing but a JSON array of data, but for some reason, my Angular app is unable to read it using $http, either

angular.module('nbd7AppApp')
  .controller('BlogListCtrl', ['$scope', '$http', function ($scope, $http) {
    $http.get('http://mylocalsite/blogs/json'})
      .success(function(data) {
        $scope.nodes = data;
    });
  }]);

or

angular.module('nbd7AppApp')
  .controller('BlogListCtrl', ['$scope', '$http', function ($scope, $http) {
    $http({method: 'GET', url: 'http://mylocalsite/blogs/json'})
      .success(function(data) {
        $scope.nodes = data;
    });
  }]);

However, if I put the JSON into a local file and access it like so

angular.module('nbd7AppApp')
  .controller('BlogListCtrl', ['$scope', '$http', function ($scope, $http) {
    $http.get('views/blogs.json')
      .success(function(data) {
        $scope.nodes = data;
    });
  }]);

it works perfectly. Is there something I need to do differently to be able to read it from the site URL?

Thanks.

NHibernate Query Collection is containing itself

I have used Fluent Nhibernate to create some simple mappings. In this mapping I have a bag and this bag is correctly auto mapped and everything is fine (just two tables with 1:n relationship).

However, when I do a Query with a Tolist after it (the bag is an IList in the class) the collection is always containing itself recursively and infinitive. So when I look what inside the object is after the Query it looks like this:

+collection
+row1
+row2

when I open up collection, it again contains:

+collection
+row1
+row2

and so on. I can open collection unlimited so the collection is containing itself.

What is the reason for this? The problem is: When I return this data as JSON, there is always a null where the collection is because I have set JSON to ignore any loops. But this is really a sad thing. I would like to fix this thing...

Thanks!! Best, Chris