Почему люди хотят поставить и Json и XML, как произведено к их интерфейсам REST?

Select Sum(Case When processed_timestamp IS NULL
                         Then 1
                         Else 0
                 End)                                                               not_processed_count,
          Sum(Case When processed_timestamp Is Not NULL
                         Then 1
                         Else 0
                 End)                                                               processed_count,
          Count(1)                                                                total
From table

Редактирование: не читал тщательно, эти возвраты единственная строка.

38
задан 5 revs, 3 users 99% 30 October 2009 в 16:07
поделиться

9 ответов

Json is often suitable for client side scripts. It is a super-lightweight response and the most part of JavaScript frameworks come with a parser built-in. On the other side, many server side applications and languages still rely heavily on XML. Just to name one: Java.

Of course, XML can be parsed with JavaScript and Java (and the most part of other programming languages) has at least one Json parser. But at the moment this seems to be the most common practice.

Talking about the "implementation vs benefit" topic, I mostly work with Ruby and I can tell you Ruby on Rails provides the ability to create a Json or XML response in less than a couple of seconds from the same source. In this case it's not a problem and I usually add that feature if I think it could be useful.

With other technologies, for example PHP, it would require more effort and the implementation would have a different cost. Unless this would be a fundamental feature, I would probably stick with one response until I don't find the need to provide to different versions.

7
ответ дан 27 November 2019 в 03:56
поделиться

A completely different reason than what's been said so far --

REST interfaces are about Resources, and each Resource has an identifier, which are URLs. Just because you want the Resource in a different serialization, be it XML, JSON, HTML, or something else, we're still describing the same Resource.

So, instead of giving a different path to the XML vs. the JSON one, we use the 'Accept' header to determine what the client is interested in. In some cases, services use the 'Accept-Language' header to determine what language they should use for their metadata.

If we assign different identifiers to different serializations of the records, for the semantic web, we then have to embed extra information to link to all of the records that describe the 'same' object.

You can find more information about these efforts under the term Linked Data, although that typically refers to using RDF at the serialization.

update : with the discussion of linking to specific formats, I'd also recommend people consider reading up on the Functional Requirements for Bibliographic Records (aka FRBR), which has a conceptual model for the relationships between 'Book' as an abstract 'Work', vs. the physical 'Item', and the levels in between. There has been a bit of discussion in the library, information and semantic web communities on FRBR, including how it relates to digital objects.

Basically, the issue is that you can assign identifiers at a number of levels (eg, the Resource, and the text of the metadata about the Resource, or the serialization of the text of the metadata about the Resource), and each have their own use.

You might also see OAI-ORE for a specification for reporting relationships between objects, including alternate formats or languages.

11
ответ дан 27 November 2019 в 03:56
поделиться

I have not direct insight into this as I only produce REST interfaces. for "internal" consumption.

I'm guessing providers of public APIs are merely "hedging their bet", in this ever- evolving, fast paced and competitive environment.

Furthermore, for hanlding relatively simple object models (which most of these probably are), the extra effort to handle both format is probably minimal and hence worthwhile.

1
ответ дан 27 November 2019 в 03:56
поделиться

I think the "why people do it" is pretty situational. If developing an application for a potential wide range of clients, supporting multiple content types might increase marketability - both to people who understand what different content types mean and to people who don't, but like things that support today's latest and greatest buzzwords.

Some reasons for supporting both are probably more technically justified. An application might require the ability for ajaxy browser clients to grab information for pages (for which JSON would be good), and also might need to support some standalone API clients that may do background or batch processing, for which XML libraries are more convenient.

I should hope that using content negotiation would be preferred over different endpoints, since using different endpoints would give REST resources multiple URIs for the same resource, which can make for an ambiguous and sometimes confusing API.

In the end, I think the "worth the effort" value solely depends on whether or not you know you can get the return on your investment in supporting multiple content types. If nobody's going to use one of the two content types, why support both? Sure they might be cool, but in a lot of cases probably fall under YAGNI as well.

1
ответ дан 27 November 2019 в 03:56
поделиться

I wouldn't read too much into it. I think some developers prefer one over the other and (especially depending on your framework) it's pretty easy to provide both.

Most of the APIs I've seen that take this approach don't bother with XML namespaces

0
ответ дан 27 November 2019 в 03:56
поделиться

Really a lot of developers don't understand JSON. I know it's easy light weight etc., but a lot of programmers don't want to spend the cycles to figure it out. They know XML, they are comfortable with it, and at the end of the day, that's really what they want to use. JSON also has this stigma of being associated with JavaScript, and that automatically makes it evil to a lot of people.

Supporting both really depends on the audience you are writing the API for, if it's a lot of business programmers who use older technologies, then yes, it's worth supporting both. If you're building it for the part of the tech industry that wants to be close to the edge, then it may not be worth supporting xml. Where I work, we have to support both, and it's worth it for us to do so. We know our clients and what they want and they pay us to provide that for them.

0
ответ дан 27 November 2019 в 03:56
поделиться

In many cases the service started out with XMP / SOAP, that was the only solution a few years ago. However recently (last 2 years or so) JSON has become more and more popular, so most services decided to also support JSON, and since they already had an XML interface they just kept it

0
ответ дан 27 November 2019 в 03:56
поделиться

Personally, I prefer to only server JSON as it avoids an angle tax on bandwidth. Also, the fact that JSON is a very lean spec is appealing as well.

From experience, Java and C# developers like the ability to have XML reflected in their objects; this creates a static-typing euphoria effect where things can't go wrong as JSON is more prone to dynamic behavior (i.e. mysticism or lispism).

PHP and Ruby programmers tend not to care.

AJAX developers prefer JSON as eval() is their parser (which is built-in and fast).

0
ответ дан 27 November 2019 в 03:56
поделиться

Я сам написал довольно подробную статью о Истории веб-служб REST, SOAP, POX и JSON .В основном подробно рассказывается о существовании и преимуществах различных опций, к сожалению, здесь слишком долго перечислять все содержимое.

По сути, XML более подробный, более строгий и поддающийся проверке, что делает его хорошим кандидатом для взаимодействия, но не настолько хорошим программным обеспечением для большинства языков программирования. Он также поддерживает концепцию схемы (т. Е. Метаданные о данных), которые можно найти в документах XSD / DTD. WSDL является расширением XSD и также поддерживает бесконечное описание веб-служб (например, веб-службы SOAP).

JSON - это более легкий текстовый формат со слабой типизацией, который фактически является «сериализованным JSON» для обеспечения наилучшего программного соответствия JavaScript, поскольку строка JSON может быть изначально преобразована eval () в объект JavaScript. Отсутствие пространств имен и концепций, атрибутов / элементов делает его также лучше подходящим для большинства других языков программирования. К сожалению, он поддерживает только основные типы: Number, String, Boolean, Object и Arrays. Что не делает его лучшим выбором для взаимодействия.

У меня есть несколько тестов базы данных Northwind , которые сравнивают эти два, и похоже, что XML в среднем 2x размер JSON для эквивалентного набора данных. Хотя, если ваш XML-документ содержит много разных пространств имен, полезная нагрузка может выйти за рамки этого.

3
ответ дан 27 November 2019 в 03:56
поделиться
Другие вопросы по тегам:

Похожие вопросы: