Deserialize JSON Object Sent from Android App to Wcf Webservice

Deserialize JSON object sent from Android app to WCF webservice

@Tobias, This is not an answer. But since it was a little bit long for comment, I post it here. Maybe it can help to diagnose your problem. [A full working code].

public void TestWCFService()
{
//Start Server
Task.Factory.StartNew(
(_) =>{
Uri baseAddress = new Uri("http://localhost:8080/Test");
WebServiceHost host = new WebServiceHost(typeof(TestService), baseAddress);
host.Open();
},null,TaskCreationOptions.LongRunning).Wait();

//Client
var jsonString = new JavaScriptSerializer().Serialize(new { xaction = new { Imei = "121212", FileName = "Finger.NST" } });
WebClient wc = new WebClient();
wc.Headers.Add("Content-Type", "application/json");
var result = wc.UploadString("http://localhost:8080/Test/Hello", jsonString);
}

[ServiceContract]
public class TestService
{
[OperationContract]
[WebInvoke(RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
public User Hello(Transaction xaction)
{
return new User() { Id = 1, Name = "Joe", Xaction = xaction };
}

public class User
{
public int Id { get; set; }
public string Name { get; set; }
public Transaction Xaction { get; set; }
}

public class Transaction
{
public string Imei { get; set; }
public string FileName { get; set; }
}
}

How to pass and consume a JSON parameter to/with RESTful WCF service?

If you want to create a WCF operation to receive that JSON input, you'll need to define a data contract which maps to that input. There are a few tools which do that automatically, including one which I wrote a while back at http://jsontodatacontract.azurewebsites.net/ (more details on how this tool was written at this blog post). The tool generated this class, which you can use:

// Type created for JSON at <<root>>
[System.Runtime.Serialization.DataContractAttribute()]
public partial class Person
{

[System.Runtime.Serialization.DataMemberAttribute()]
public int age;

[System.Runtime.Serialization.DataMemberAttribute()]
public string name;

[System.Runtime.Serialization.DataMemberAttribute()]
public string[] messages;

[System.Runtime.Serialization.DataMemberAttribute()]
public string favoriteColor;

[System.Runtime.Serialization.DataMemberAttribute()]
public string petName;

[System.Runtime.Serialization.DataMemberAttribute()]
public string IQ;
}

Next, you need to define an operation contract to receive that. Since the JSON needs to go in the body of the request, the most natural HTTP method to use is POST, so you can define the operation as below: the method being "POST" and the style being "Bare" (which means that your JSON maps directly to the parameter). Notice that you can even omit the Method and BodyStyle properties, since "POST" and WebMessageBodyStyle.Bare are their default values, respectively).

[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Bare)]
public Person FindPerson(Peron lookUpPerson)
{
Person found = null;
// Implementation that finds the Person and sets 'found'
return found;
}

Now, at the method you have the input mapped to lookupPerson. How you will implement the logic of your method is up to you.

Update after comment

One example of calling the service using JavaScript (via jQuery) can be found below.

var input = '{
"age":100,
"name":"foo",
"messages":["msg 1","msg 2","msg 3"],
"favoriteColor" : "blue",
"petName" : "Godzilla",
"IQ" : "QuiteLow"
}';
var endpointAddress = "http://your.server.com/app/service.svc";
var url = endpointAddress + "/FindPerson";
$.ajax({
type: 'POST',
url: url,
contentType: 'application/json',
data: input,
success: function(result) {
alert(JSON.stringify(result));
}
});

Android JSon Object Not readable in dotnet webservice for insert operation in REST

Having never used the Json Serializer, but having a slight clue about how WCF does its deserialization I would say you can't have StringBuilder as a parameter.

Just change your operation signature to:

bool CreateCustomer(Customer customer);

WCF wants to do the serialization and deserialization itself, so let it.

Passing JSON object from Android Client to WCF Restful service in C#

The name of the wrapper should be the parameter name, not the type name. In your service, the operation is defined as

[WebInvoke(...)] 
string Login(User user);

So the input should be passed as

{"user":{"UserName":"123","Pass":"123","Device":"123"}}

(notice the lowercase "user" object name).

Consume a WCF web service with Post Params with Android

My french is not that good, but I'm guessing that you have to explicitly set the Content-type of your request. The webservice accepts json but the incoming request is raw.

Try adding application/json as the content-type in your request. Something like this:

post.setHeader("Content-Type", "application/json");

Send information from android application to a Web Service and back

I think the best way to achieve your work is using HTTP post, to do that you need 5 things:

1) do a Json object: JSONObject jsonobj = new JSONObject(); //you need to fill this object

2) Create a http client:

DefaultHttpClient httpclient = new DefaultHttpClient();

3) create a http response and a http request:

HttpResponse httpresponse;
HttpPost httppostreq;

3) complete your http request:

httppostreq = new HttpPost(SERVER_URL);

4) attach the json object (the one you will send):

StringEntity se = new StringEntity(jsonobj.toString());
se.setContentType("application/json;charset=UTF-8");
httppostreq.setEntity(se);

5) to get the response: httpresponse = httpclient.execute(httppostreq); //as a Json object

2 observations: you need to catch the possibles exceptions and always a http request must be done in a different thread.

Get & Post image from Android to WCF

I don't know what error you get from android side but you can also try with HttpUrlConnection to send data check this answer.

Or look this answer if you want to use HttpPost:
https://stackoverflow.com/questions/6360207/android-sending-a-byte-array-via-http-post

JSONObject args = new JSONObject();
args.put("Area", editTextPrice.getText().toString());
args.put("Description", editTextDescription.getText().toString())

ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
byte[] b = baos.toByteArray();

String encodedImage = Base64.encodeToString(b , Base64.DEFAULT);
args.put("image",encodedImage);

//You can also use NameValuePair instead JSON
//like : nameValuePairs.add(new BasicNameValuePair("Area", editTextPrice.getText().toString());
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("data", arg.toString()));

httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));

// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);

On C# get image string then change to bytearray

public class Message
{

public string Area {get;set;}
public string Description {get;set;}
public string Image {get;set;}
}
Message message = new JavaScriptSerializer().Deserialize<Message>(result);

byte[] imageData = Convert.FromBase64String(message.image);
MemoryStream ms = new MemoryStream(imageData);
Image returnImage = Image.FromStream(ms);

DataContractJsonSerializerOperationFormatter does not deserialize using JSON.NET

I am using Newtonsoft to serialize the date format to hold ISODate format. I was able to solve my problem doing this:

Test.cs:

[DataContract]
public class Test
{
public DateTime xaaaaaa { get; set; }

[DataMember(Name = "xaaaaaa")]
private string HiredForSerialization { get; set; }

[OnSerializing]
void OnSerializing(StreamingContext ctx)
{
this.HiredForSerialization = JsonConvert.SerializeObject(this.xaaaaaa).Replace('"',' ').Trim();
}

[OnDeserialized]
void OnDeserialized(StreamingContext ctx)
{
this.xaaaaaa = DateTime.Parse(this.HiredForSerialization);
}

}

jQuery:

$.ajax({
url: "Transfer.svc/new/one",
type: "POST",
contentType: "application/json; charset=utf-8",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
data: JSON.stringify({ aa: { xaaaaaa: "2014-05-31T18:30:00.000Z" } }),
dataType: 'json',
processData: true,
success: function (msg) {
tester = msg.helloWorldResult; //"2014-06-01T00:00:00+05:30"
},
error: function (msg) {
var y = 0;
}
});

Date I selected from the date picker (jQuery):

Selected date : 1st-Jun-2014

WCF Service Looks like this:

    [OperationContract]
[WebInvoke(Method = "POST",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "new/one")]
public Test helloWorld(Test aa)
{
return aa;
}

This works great!



Related Topics



Leave a reply



Submit