0

Can I use JSON to send a complex object from one pc to another?

From my understanding of JSON you can just stringy that object, then send the string to the other pc and then destringify it and rebuild the object again.

But now how does it know what object I have sent it? cause I could send it object A or object B ?

Is there a way to find out what object I have sent it? Or is part of JSON knowing what type of object you are going to receive?

Zapnologica
  • 22,170
  • 44
  • 158
  • 253
  • It does not know. Sender and receiver should *somehow* agree on the type (you may inject some type info into the json for ex). – L.B Feb 18 '14 at 10:46

4 Answers4

1

Can I use JSON to send a complex object from one pc to another?

Yes

But now how does it know what object I have sent it? cause I could send it object A or object B ?

The receiver knows when it deserialises the Json. The receiver needs to know what the Json will look like or dynamically deserialise it if it cannot know. See this SO answer on dynamically deserialising.

dynamic something = JsonConvert.DeserializeObject(json);
Community
  • 1
  • 1
Sam Leach
  • 12,746
  • 9
  • 45
  • 73
0

If as client you use as an instance of a class like Spring RestTemplate, you can tell it which class it should expect the JSon to be an instance of, and convert it accordingly.

http://www.springframework.net/rest/doc-latest/reference/html/resttemplate.html

Andres
  • 10,561
  • 4
  • 45
  • 63
0

But now how does it know what object I have sent it? cause I could send it object A or object B ?

The other side should be aware to the fact that a JSON object has been received in a string format and accordingly, to parse or deserialize it properly, just like in the following example, which takes a JSON string and parse it to JSON or C# object:

In JavaScript:

var jsonObj = JSON.parse(yourJsonString);

In C#:

dynamic jsonObj = JsonConvert.DeserializeObject(yourJsonString);

In addition, if it's an HTTP request, you can specify the content-type to: application/json. This way, the receiver side could analyze it and understand it is a JSON string.

Read more:

Yair Nevet
  • 12,725
  • 14
  • 66
  • 108
0

JSON is the string representation of data.

You either know what the other side expects or need to send additional meta-data.

Very often you know exactly what kind of object has been sent.

Adding additional meta-data could easily be done automatically (and I am sure there are a lot of libraries available):

{
  class: A
  entity: {...}
}
close2
  • 308
  • 1
  • 7